public class HuiWen { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.nextLine(); //可以输入空格 System.out.println(isPalindrome(s)); }
public static boolean isPalindrome(String s) { StringBuilder sb=new StringBuilder(); int len=s.length(); for(int i=0;i<len;i++){ if(s.charAt(i)>='0'&&s.charAt(i)<='9'||s.charAt(i)>='a'&&s.charAt(i)<='z'){ sb.append(s.charAt(i)); } if(s.charAt(i)>='A'&&s.charAt(i)<='Z'){ sb.append((char)(s.charAt(i)+32)); } } int left=0; int right=sb.length()-1; while(left<right){ if(sb.charAt(left)==sb.charAt(right)){ left++; right--; }else{ return false; } } return true; }
public class WuChongFuZiChuan { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); System.out.println(lengthOfLongestSubstring(s)); }
public static int lengthOfLongestSubstring(String s) { int n = s.length(); //获取字符串长度 int ans = 0; Map<Character, Integer> map = new HashMap<>(); int start=0; for (int end = 0; end < n; end++) { char a = s.charAt(end); //获取当前位置字符 if (map.containsKey(a)) { start = Math.max(map.get(a), start); } ans = Math.max(ans, end - start + 1); //算距离 map.put(s.charAt(end), end + 1); //当前map里面存当前字符串字符和下标 } return ans ; }
public class FanZhuan { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(reverse(n)); }
public static int reverse(int n) { int res=0; //最后结果 String temp=""; //整数转字符串 反转之后的结果 if(n>0){ temp=new StringBuilder(String.valueOf(n)).reverse().toString(); }else{ temp="-"+new StringBuilder(String.valueOf(n).substring(1)).reverse().toString(); //从第二个位置开始 第一个是-号 } if(temp.equals("")){ temp = "0"; //n为0 }
class Solution { public int romanToInt(String s) { int sum = 0; int preNum = getValue(s.charAt(0)); for(int i = 1;i < s.length(); i ++) { int num = getValue(s.charAt(i)); if(preNum < num) { sum -= preNum; } else { sum += preNum; } preNum = num; } sum += preNum; return sum; } private int getValue(char ch) { switch(ch) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } }
public class LuoMa { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); String[] strs=new String[n]; for(int i=0;i<n;i++){ strs[i]=input.next(); } System.out.println(longestCommonPrefix(strs)); }
public class ShengKuoHao { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(generateParenthesis(n)); }
public static List<String> generateParenthesis(int n) { List<String> res=new ArrayList<>(); if (n == 0) { return res; //长度为0返回空 } // 执行深度优先遍历,搜索可能的结果 dfs("", n, n, res); return res; }
public class LiangShuChuFFa { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(countAndSay(n)); }
public static String countAndSay(int n) { String res = "1"; for (int i = 2; i <= n; i++) { StringBuilder temp = new StringBuilder(); for (int j = 0; j <res.length(); j++) { int count = 1; while (j + 1 < res.length() && res.charAt(j) == res.charAt(j + 1)) { //j+1小心越界 count++; //记录出现几次 j++; //下标更新 } temp.append(count).append(res.charAt(j)); //添加某个数出现了多少次 2次2 3次4等等 } res = temp.toString(); //res接上一次的结果 } return res; }
public int[] plusOne(int[] digits) { int n = digits.length; for(int i = n -1;i>=0;i--){ //倒序 if(digits[i] == 9){ digits[i] = 0; //如果当前位置是9 就要变为0 }else{ digits[i]++; //其他数字就直接+1 return digits; //然后返回 } } int[] a = new int [n+1]; //新建数组a存放结果 a[0]=1; //给999这+1增加进位留一位为1 return a; }
结果
X的平方根(二分法)
题目
分析
主要二分法找k的平方是不是小于x,然后二分法找
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Solution { public int mySqrt(int x) { int l = 0, r = x, ans = -1; //找不到就是-1 while (l <= r) { int mid = l + (r - l) / 2; //中间位置 if ((long)mid * mid <= x) { ans = mid; l = mid + 1; //在右边 } else { r = mid - 1; //在左边 } } return ans; } }
public class Jump { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); //输入字符串 System.out.println(partition(s)); //调用方法获取结果 }
public static List<List<String>> partition(String s) { List<List<String>> res = new ArrayList<>(); //res接受结果 backtrack(res, s, new ArrayList<String>()); //调用方法 return res; }
private static void backtrack(List<List<String>> res, String s, ArrayList<String> tmp) { if (s == null || s.length() == 0) { res.add(new ArrayList<>(tmp)); //如果字符串不存在 就返回tmp新的list集合 [] } for (int i = 1; i <= s.length(); i++) { if (isPalidrome(s.substring(0, i))) { //如果截取的这部分是回文串 tmp.add(s.substring(0, i)); //tmp集合存放s的部分 backtrack(res, s.substring(i, s.length()), tmp); //找i之后的部分 前面的s被tmp集合用了 tmp.remove(tmp.size() - 1); //回溯 } } }
private static boolean isPalidrome(String sb) { int left = 0; //左指针 int right = sb.length() - 1; //右指针 while (left < right) { //左右不碰面 if (sb.charAt(left) != sb.charAt(right)) { return false; //如果左右不相等 就返回false } left++; //向中间靠拢 right--; } return true; }
public class Jump { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); System.out.println(isHappy(n)); }
public static boolean isHappy(int n) { Set<Integer> set=new HashSet<>(); while(n!=1&&!set.contains(n)) { //没出现 set.add(n); //set集合里面添加n n = getNext(n); //调用方法得到新的n } return n == 1; //判断结果是不是1 }
private static int getNext(int n) { int totalSum = 0; while (n > 0) { int d = n % 10; //拆分 n = n / 10; totalSum += d * d; //得到n这个数字每一位最终的结果 } return totalSum; }
public class Jump { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); long res=trailingZeroes(n); //获阶乘的结果 int ge=jige(res); System.out.println(ge); }
public static long trailingZeroes(int n) { long res=0; if(n==0||n==1){ res=1; //0!=1 } if(n==2){ res=2; //2!=2*1=2 }else{ res=trailingZeroes(n-1)*n; } return res; }
private static int jige(long res) { int ge=0; //0的个数 long j=0; while(res!=0){ j=res%10; if(j==0){ ge++; } if(j!=0){ break; } res=res/10; } return ge; }
}
//第二种:得到5的个数
public static int trailingZeroes(int n) { int count = 0; //获取的结果 //一个5提供一个0,一个25提供2个0; while (n > 0) { //n大于0就行 count+=n/5; n=n/5; } return count; }
class Solution { private class LargerNumberComparator implements Comparator<String> { @Override public int compare(String a, String b) { String o1 = a + b; String o2 = b + a; return o2.compareTo(o1); } }
public String largestNumber(int[] nums) { String[] s = new String[nums.length]; for (int i = 0; i < nums.length; i++) { s[i] = String.valueOf(nums[i]); //将对应的数字传到s的字符串数组 } Arrays.sort(s, new LargerNumberComparator()); //排序 if (s[0].equals("0")) { return "0"; //如果有0就返回0 }
String res = new String(); for (String numAsStr : s) { res+= numAsStr; //循环将s数组贴合在字符串res上 }
return res; } }
结果
旋转数组(新建数组放)
题目
分析
1. 新建数组b
2. 通过下标的倾斜存入新的数组b
3. 主函数调用输出
代码
1 2 3 4 5 6 7 8 9
public void rotate(int[] nums, int k) { int[] a = new int[nums.length]; for (int i = 0; i < nums.length; i++) { a[(i + k) % nums.length] = nums[i]; } for (int i = 0; i < nums.length; i++) { nums[i] = a[i]; } }
结果
颠倒二进制位(位运算)
题目
分析
主要基于位运算!!!
代码
1 2 3 4 5 6 7 8 9 10 11 12
public int reverseBits(int n) { int res = 0; int count = 0; while (count < 32) { res <<= 1; //res 左移一位空出位置 res |= (n & 1); //得到的最低位加过来 n >>= 1;//原数字右移一位去掉已经处理过的最低位 count++; } return res; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } moveZeroes(a); System.out.println(Arrays.toString(a)); }
//1.排序之后如果前后一样就重复输出 public static int findDuplicate(int[] nums) { int res=0; Arrays.sort(nums); for (int i = 0; i < nums.length-1; i++) { if(nums[i]==nums[i+1]){ return nums[i]; } } return res; }
//2.二分法 public static int findDuplicate(int[] nums) { int n = nums.length; int l = 1, r = n - 1, ans = -1; while (l <= r) { //左<=右 int mid = (l + r) >> 1; //中间位置 int cnt = 0; for (int i = 0; i < n; ++i) { if (nums[i] <= mid) { cnt++; } } if (cnt <= mid) { l = mid + 1; //重复的在右边 } else { r = mid - 1; //重复的在左边 ans = mid; } } return ans; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } System.out.println(lengthOfLIS(a)); }
public static int lengthOfLIS(int[] nums) { if (nums.length == 0) { return 0; //数组长度为0 } int[] dp = new int[nums.length]; Arrays.fill(dp, 1); //数组都补充1 int res = 0; for (int i = 0; i < nums.length; i++) { for(int j=0;j<i;j++){ if(nums[j] < nums[i]){ //说明可以贴在后面 dp[i] = Math.max(dp[i], dp[j] + 1); } } res = Math.max(res, dp[i]); } return res; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } int amount=input.nextInt(); System.out.println(coinChange(a,amount)); }
public static int coinChange(int[] coins, int amount) { //零钱相当于物品,总金额相当于背包容量 int [] dp=new int[amount+1];//dp[i][j]:对前i个零钱,选若干兑换总金额为j的整钱,最少需要的零钱个数为dp[i][j]
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } System.out.println(increasingTriplet(a)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for (int i = 0; i <n ; i++) { a[i]=input.nextInt(); } int k=input.nextInt(); System.out.println(Arrays.toString(topKFrequent(a,k))); }
public static int[] topKFrequent(int[] nums, int k) { //存放key-value这样的形式 存放每个元素出现次数 Map<Integer,Integer> map=new HashMap<>(); //进行排序 PriorityQueue<Map.Entry<Integer, Integer>> maxheap = new PriorityQueue<>((a,b) -> b.getValue() - a.getValue()); //存放结果的数组 int[] result = new int[k]; for (int i = 0; i < nums.length; i++) { map.put(nums[i],map.getOrDefault(nums[i],0)+1); //遍历存放每个key对应的value } for(Map.Entry<Integer, Integer> m : map.entrySet()){ maxheap.offer(m); //按照键值对放入maxhead中 } //倒序输出k个值就是结果 for(int i = 0; i < k; i++){ result[i] = maxheap.poll().getKey(); } return result; }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[][] a=new int[][]{{1,5,9},{10,11,13},{12,13,15}}; int m=input.nextInt(); System.out.println(kthSmallest(a,m)); }
public static int kthSmallest(int[][] matrix, int k) { int res=0; int len=matrix.length; //数组的行和列 int[] a=new int[len*len]; int z=0; for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ a[z++]=matrix[i][j]; } } Arrays.sort(a); //进行排序 return a[k-1]; //返回第8个 }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); System.out.println(firstUniqChar(s)); }
public static int firstUniqChar(String s) { //存放字符出现次数和对应字符(键值对) HashMap<Character, Integer> count = new HashMap<Character, Integer>(); //字符串长度 int n = s.length(); //遍历存入map集合 for (int i = 0; i < n; i++) { char c = s.charAt(i); count.put(c, count.getOrDefault(c, 0) + 1); } //遍历找谁出现次数是1次 for (int i = 0; i < n; i++) { if (count.get(s.charAt(i)) == 1) return i; } return -1; //找不到返回-1 }
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { Map<Integer, Integer> map = new HashMap<>(); //Map<Integer, Integer> map = new HashMap<>(); int res = 0; for(int i = 0;i<A.length;i++){ for(int j= 0;j<B.length;j++){ int sumAB = A[i]+B[j]; if(map.containsKey(sumAB)) map.put(sumAB,map.get(sumAB)+1); else map.put(sumAB,1); } }
for(int i = 0;i<C.length;i++){ for(int j = 0;j<D.length;j++){ int sumCD = -(C[i]+D[j]); if(map.containsKey(sumCD)) res += map.get(sumCD); //增加有这个配对的key的value值 } } return res; }
public class BianWeiArr { public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] a={"eat","tea","tan","ate","nat","bat"}; System.out.println(groupAnagrams(a)); }
class WordsFrequency { Map<String,Integer> recMap = new HashMap<>(); public WordsFrequency(String[] book) { for(int i=0;i<book.length;i++) { if(!recMap.containsKey(book[i])) { recMap.put(book[i],1); }else { recMap.put(book[i], recMap.get(book[i])+1); } } }
public int get(String word) { if(recMap.containsKey(word)) { return recMap.get(word); } return 0; } }
/** * Your WordsFrequency object will be instantiated and called as such: * WordsFrequency obj = new WordsFrequency(book); * int param_1 = obj.get(word); */
public class OnlyOne { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.next(); System.out.println(firstUniqChar(s)); }
public class ShuDuiHe { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for(int i=0;i<a.length;i++){ a[i]=input.nextInt(); } int target=input.nextInt(); System.out.println(pairSums(a,target)); }
public static List<List<Integer>> pairSums(int[] nums, int target) { List<List<Integer>> ans=new LinkedList<>(); Arrays.sort(nums); //对数组进行排序 int start=0; int end=nums.length-1; for(;start<end;){ int sum = nums[start] + nums[end]; if (sum < target) { //要变大一些 start++; } else if (sum > target){ //要变小一些 end--; } else { //刚好符合 List<Integer> list = new LinkedList<>(); //新成立list集合 list.add(nums[start]); //存进去start和end位置的值 list.add(nums[end]); ans.add(list); //最终结果添加list集合 start++; //缩小范围 end--; } } return ans; }
public class SouSuoXuanZhuanArr { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) { a[i]=input.nextInt(); } int target=input.nextInt(); System.out.println(search(a,target)); }
public static int search(int[] arr, int target) { int min=Integer.MAX_VALUE; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); //设置map集合存储 for(int i=0;i<arr.length;i++){ map.put(arr[i],i); //将数组的集合内容和下标存储下去 } if(map.containsKey(target)){ //如果map里面有这个就获取map对应下标 int i=map.get(target); min=Math.min(min,i); //多个出现就得到最小的那个索引 return min; } return -1; //默认找不到就是-1 }
public class ZuiChangZiString { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.next(); System.out.println(lengthOfLongestSubstring(s)); }
public static int lengthOfLongestSubstring(String s) { Map<Character, Integer> map = new HashMap<>(); int res = 0, tmp = 0; for(int j = 0; j < s.length(); j++) { // getOrDefault代表当哈希表包含键key时返回对应value,不包含时返回默认值default。 int left = map.getOrDefault(s.charAt(j),-1);
public class SanBu { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(waysToStep(n)); }
public static int waysToStep(int n) { int a=1; //一个台阶一种走法 1 int b=2; //二个台阶两种走法 1+1 / 2 int c=4; //三个台阶四种走法 1+1+1 / 1+2 / 2+1 / 3 int d=0; for(int i=1;i<n;i++){ d=(a+(b+c)%1000000007)%1000000007; a=b; b=c; c=d; } return a; }
}
结果
面试08.02 迷路的机器人
题目
分析
代码
1 2
结果
面试08.11 硬币
题目
分析
代码
1 2
结果
面试17.16 按摩师/打家劫舍(a[0]+a[2]和a[1]对比)
题目
分析
1. 思路:(当前+前两个) ?(前一个)
2. 第一种o(n):dp[i]=Math.max(dp[i-1],nums[i]+dp[i-2]);
3. 第二种o(1): a b c三个变量递进循环
public class AnMoShi { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=input.nextInt(); } System.out.println(massage(a)); }
//O(n) public static int massage(int[] nums) { int n = nums.length; //数组长度 if (n == 0) { return 0; //如果数组长度为0就返回0 } if (n == 1) { return nums[0]; //如果只有一个就返回这个值 } int[] dp = new int[n]; //存放结果 dp[0] = nums[0]; //第一个值就是当前的第一个 dp[1]=Math.max(nums[0], nums[1]); //判断是1开始还是2开始 for(int i=2;i<n;i++){ dp[i]=Math.max(dp[i-1],nums[i]+dp[i-2]); }
return dp[n-1]; //返回最后一个值 }
//O(1) public int massage(int[] nums) { int a = 0, b = 0; for (int i = 0; i < nums.length; i++) { int c = Math.max(b, a + nums[i]); a = b; b = c; } return b; }
class Solution { public int[] swapNumbers(int[] numbers) { int[] a=new int[2]; a[0]=numbers[1]; //原来第二个数到第一个 a[1]=numbers[0]; //原来第一个数到第二个 return a; } }
结果
面试16.05 阶乘尾数(大数乘法/5的因数)
题目
分析
1. 先计算出阶乘的值 然后按位输出判断0的个数
2. 判断5的因数个数(多少个数字能整除5)
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class JieChengWeiShu { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(trailingZeroes(n)); }
public static int trailingZeroes(int n) { int ans=0; while(n>0){ ans+=n/5; //不断的/5求次数 n/=5; } return ans; }
public class ErCiShu { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int jie=0; for(int i=1;i<=n;i++){ //从1到n都调用方法得到结果 jie+=numberOf2sInRange(i); } System.out.println(jie); }
public static int numberOf2sInRange(int n) { int ci=0; //记录2的个数 int m=1; while (n != 0) { m = n % 10; if (m == 2) { ci++; //每一位是2就ci++计数 } n = n / 10; } return ci; }
public class DiKShu { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(getKthMagicNumber(n)); }
public class JianShengZi { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(cuttingRope(n)); }
public static int cuttingRope(int n) { if(n <= 3) { return n - 1; //必须剪出一段长度为1的绳子 } int a=n/3; int b=n%3; //n=3a*b if(b==0){ return (int)Math.pow(3, a); //3的a次方 } if(b==1){ return (int)Math.pow(3, a - 1) * 4; } return (int)Math.pow(3, a) * 2; // 3 3 5(45) <<< 3 4 4(3*4*4=48) }
}
结果
面试14-II 剪绳子(分情况讨论)
题目
分析
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Solution { public int cuttingRope(int n) { if(n <= 3) return n - 1; int b = n % 3, p = 1000000007; long rem = 1, x = 3; for(int a = n / 3 - 1; a > 0; a /= 2) { if(a % 2 == 1) rem = (rem * x) % p; x = (x * x) % p; } if(b == 0) return (int)(rem * 3 % p); if(b == 1) return (int)(rem * 4 % p); return (int)(rem * 6 % p); } }
public interface YiDaoN { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(Arrays.toString(printNumbers(n))); }
public class Yi { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int jie=0; for(int i=1;i<=n;i++){ //从1到n都调用方法得到结果 jie+=numberOf2sInRange(i); } System.out.println(jie); }
public static int numberOf2sInRange(int n) { int ci=0; //记录1的个数 int m=1; while (n != 0) { m = n % 10; if (m == 1) { ci++; //每一位是1就ci++计数 } n = n / 10; } return ci; }
public class ChouShu { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(nthUglyNumber(n)); }
public static int nthUglyNumber(int n) { int[] a=new int[n]; a[0]=1; int p2=0; int p3=0; int p5=0; for(int i=1;i<n;i++){ a[i]=Math.min(a[p2]*2,Math.min(a[p3]*3,a[p5]*5)); //就看哪个乘最小 放入当前位置 if(a[i]==a[p2]*2){ p2++; //哪个满足就要指针后移 为了下轮的判断 } if(a[i]==a[p3]*3){ p3++; } if(a[i]==a[p5]*5){ p5++; } }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); //输入要判断的多大值 find(n); //调用方法返回结果 }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.nextLine(); System.out.println(zhuan(s)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); //输入10进制 System.out.println(find(n)); }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(hammingDistance(1,4)); }
public static int hammingDistance(int x, int y) { int xor = x ^ y; // 0001异或0100 --> 0101就是5 System.out.println("异或结果"+xor); int distance = 0; //测量距离 while (xor != 0) { if (xor % 2 == 1) //不同的话就是异或的结果为1的地方 distance += 1; xor = xor /2; //变小 } return distance; //返回距离 }
}
结果
增减字符串匹配(双指针移动)
题目
分析
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public static int[] diStringMatch(String s) { int n=s.length(); //获取字符串长度n int[] res=new int[n+1]; //结果长为n+1 //确定左右指针 int left=0; int right=n; for (int i = 0; i < n; i++) { char temp = s.charAt(i); //获取字符串当前字符 if (temp == 'I') { //递增 res[i]=left++; } if (temp == 'D') { //递减 res[i]=right--; } } res[n]=left; //最后一个n+1的位置没有判断 添加left进去 return res; }
结果
最长特殊序列I(判断字符串长度)
题目
分析
代码
1 2 3 4 5 6
public int findLUSlength(String a, String b) { if (a.equals(b)) return -1; //如果两个字符串相同 返回-1 return Math.max(a.length(), b.length()); //如果不相同就看谁的更长度更长了 }
public int numWaterBottles(int sum, int numExchange) { int total = sum; //首先将sum加入 while (sum >= numExchange) { //手里的酒瓶数 < 要兑换酒瓶数量 //change表示的是兑换成酒的数量 int change = sum / numExchange; //total再加上兑换的酒 total += change; //瓶子数量变为兑换成酒的数量加上没有兑换成酒的数量 sum = change + sum % numExchange; //更新手里的总数 } return total; }
//第一种 每一个斜对角线的hang-lie是相同的 // 将第一个hang-lie的元素存入map 后面判断错误返回false public boolean isToeplitzMatrix(int[][] matrix) { Map<Integer, Integer> groups = new HashMap(); for (int r = 0; r < matrix.length; ++r) { for (int c = 0; c < matrix[0].length; ++c) { if (!groups.containsKey(r-c)) groups.put(r-c, matrix[r][c]); else if (groups.get(r-c) != matrix[r][c]) return false; // } } return true; }
//第二种 从(1,1)开始只是对照上一层的(i-1,j-1)元素 public boolean isToeplitzMatrix(int[][] matrix) { int column = matrix[0].length; for (int i = 1; i < matrix.length; i++) { for (int j = 1; j < column; j++) { if (matrix[i][j] != matrix[i - 1][j - 1]) return false; //如果不同就弹出false } } return true; }
public static int minMoves(int[] a) { Arrays.sort(a); //对a数组进行排序 int res=0; int count=a.length-1; //每次能够使n-1个元素增加1 for (int i = 0; i < a.length; i++) { res+=a[i]-a[0]; //计算比a【0】多多少 } return res; }
public class ChengFa { public static void main(String[] args) { Scanner input = new Scanner(System.in); int a=input.nextInt(); int b=input.nextInt(); System.out.println(multiply(a,b)); }
public static int multiply(int a, int b) { int sum=0; for(int i=0;i<b;i++){ sum+=a; //乘法就相当于多次加法 } return sum; }
public class TiaoShuiBan { public static void main(String[] args) { Scanner input = new Scanner(System.in); int shorter=input.nextInt(); int longer=input.nextInt(); int k=input.nextInt(); System.out.println(Arrays.toString(divingBoard(shorter,longer,k))); }
public static int[] divingBoard(int shorter, int longer, int k) { // 最小值 int min = shorter * k; //就是可能性中最小取值 // 最大值 int max = longer * k; //就是可能性中最大取值 // 差值 int difference = longer - shorter; //每一次可能中差的一次结果 //数组长度 int len=0; if (k != 0) { if (difference == 0) { //最长和最短一样: 可能性就只有一种 len = 1; } else { len = k+1; // 最长和最短不一样: 长度是k+1 } } int[] nums = new int[len]; //存放可能性的值 for (int i = 0; i <len; i++) { if (i == 0) { nums[i] = min; //最小的可能就是k次都是最短的 } else { nums[i] = nums[i-1] + difference; //后面的每一次可能就是前面的加上两者差 } } return nums; }
}
结果
面试17.12 BiNode
题目
分析
代码
1 2
结果
面试10-I 斐波那契数列(递归/动态规划)
题目
分析
1. 递归:return fib(n-1)+fib(n-2)
2. 动态规划:就是abc三个数字不断后移
sum = (a + b) % 1000000007; //第三个数字
a = b; //原来的第二个是下一轮的第一个
b = sum; //原来的第三个是下一轮的第二个
public class FeiBo { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println("递归:"+fib(n)); System.out.println("动态规划:"+dongtai(n)); } //递归 public static int fib(int n) { if(n==0){ return 0; } if(n==1){ return 1; } return fib(n-1)+fib(n-2); } //动态规划 public static int dongtai(int n) { int a = 0, b = 1, sum; for(int i = 0; i < n; i++){ sum = (a + b) % 1000000007; a = b; b = sum; } return a; }
public class QingWa { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(numWays(n)); System.out.println(numWayser(n)); }
public class ShuZhengCiFang { public static void main(String[] args) { Scanner input = new Scanner(System.in); Double x=input.nextDouble(); int n=input.nextInt(); System.out.printf("%.5f",cifang(x,n)); }
public class MinK { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=input.nextInt(); } int k=input.nextInt(); System.out.println(Arrays.toString(smallestK(a,k))); }
public class URLhua { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.nextLine(); int length=input.nextInt(); System.out.println(replaceSpaces(s,length)); }
public class HuiWenPaiLie { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.next(); System.out.println(canPermutePalindrome(s)); }
public static boolean canPermutePalindrome(String s) { Set<Character> set = new HashSet<>(); for(char c:s.toCharArray()) { if (!set.add(c)) { //如果c字符不能添加就说明是重复出现 set.remove(c); //移除第一次添加的c字符 } } return set.size()<=1; //看最后是不是只有那个奇数的一个/全是偶数的被移除了 }
public class StringYaSuo { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.nextLine(); System.out.println(compressString(s));
public class ErjinzhizhuanString { public static void main(String[] args) { Scanner input = new Scanner(System.in); Double num=input.nextDouble(); System.out.println(printBin(num)); }
public class KuoHao { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); System.out.println(generateParenthesis(n)); //调用方法 }
public static List<String> generateParenthesis(int n) { List<String> res=new ArrayList(); //特定判断 if (n == 0) { return res; } //执行深度优先遍历 dfs("",n,n,res);
return res; }
/** * @param curStr 当前递归得到的结果 * @param left 左括号还有几个可以使用 * @param right 右括号还有几个可以使用 * @param res 结果集 */ private static void dfs(String curStr, int left, int right, List<String> res) { //因为每一次尝试,都使用新的字符串变量,所以无需回溯 if(left==0&&right==0){ res.add(curStr); // 在递归终止的时候,直接把它添加到结果集即可 return ; //void不需要返回 }
// 剪枝(左<右就符合左边用的多这样不需要剪枝) if (left > right) { return; //void不需要返回 }
public class JiSuanQi { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.next(); System.out.println(calculate(s)); }
public class ZuiChangDanCi { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.nextLine(); System.out.println(reverseWords(s)); }
public static String reverseWords(String s) { String[] strs = s.trim().split(" "); // 删除首尾空格,分割字符串 StringBuilder res = new StringBuilder(); for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表 if(strs[i].equals("")){ continue; // 遇到空单词则跳过 } res.append(strs[i]+" "); // 将单词拼接至 StringBuilder } return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回 }
public class ZuoXuanZhuanString { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s=input.nextLine(); int n=input.nextInt(); System.out.println(reverseLeftWords(s,n)); }
public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); String s=input.next(); int n=input.nextInt(); System.out.println(convert(s,n)); }
public static String convert(String s, int numRows) { if(numRows<2){ //如果是0行或者1行 就直接输出s即可 return s; } //存储每一行的字符(要拼接所以要用StringBuilder类) List<StringBuilder> rows = new ArrayList<StringBuilder>(); //根据行数每行添加一个StringBuilder for(int i=0;i<numRows;i++){ rows.add(new StringBuilder()); //每一行都有一个 } int i=0; int flag=-1; for(char c:s.toCharArray()){ rows.get(i).append(c); //对应行添加进去字符 if(i==0||i==numRows-1){ flag=-flag; //到了拐角要变换flag } i=i+flag; //1的话就是往下加 -1的话就是往上加 } StringBuilder res = new StringBuilder(); //新建接住结果 for(StringBuilder row:rows) { res.append(row); //添加每一行的结果集合 } return res.toString();//最后记得转字符串 }
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(Arrays.toString(shortestToChar("loveleetcode",'e'))); }
public static int[] shortestToChar(String S, char C) { int N = S.length(); //获取字符串长度 int[] ans = new int[N]; //返回结果的ans数组
int prev=Integer.MIN_VALUE/2; //先取负数 //从左往右取结果 for (int i = 0; i < N; ++i) { //正序 if (S.charAt(i) == C) prev = i; ans[i] = i - prev; //找到相近的字符的距离 } //从右往左取结果 prev = Integer.MAX_VALUE / 2; //先取正数 for (int i = N-1; i >= 0; --i) { //倒序 if (S.charAt(i) == C) prev = i; ans[i] = Math.min(ans[i], prev - i); //找到相近的字符的距离 } return ans; //返回ans数组 }
}
结果
删除回文子序列(因为只有a和b字符)
题目
分析
代码
1 2 3 4 5 6 7 8 9 10
public int removePalindromeSub(String s) { if ("".equals(s)) { return 0; //空字符串 } if (s.equals(new StringBuilder(s).reverse().toString())){ return 1; //本身就是回文串 } return 2; //其他情况就是一次性删除所有a 然后删除b }
结果
字符串的最大公因子(辗转相除法)
题目
分析
使用辗转相除法得到最大公因子!!!
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public String gcdOfStrings(String str1, String str2) { // 假设str1是N个x,str2是M个x,那么str1+str2肯定是等于str2+str1的。 if (!(str1 + str2).equals(str2 + str1)) { return ""; } int l1=str1.length(); int l2=str2.length(); // 辗转相除法求gcd。 return str1.substring(0, gcd(l1, l2)); //截取str1的部分字符串 }
public static int gcd(int a, int b) { return b == 0? a: gcd(b, a % b); //b是0就返回a b不是0就返回a%b }
public String reverseOnlyLetters(String S) { Stack<Character> letters = new Stack(); for (char c: S.toCharArray()) if (Character.isLetter(c)) letters.push(c); //所有数字反序压栈
StringBuilder ans = new StringBuilder();
//第二次再次遍历 for (char c: S.toCharArray()) { if (Character.isLetter(c)) ans.append(letters.pop()); //如果当前位是字母 就出栈 刚好是反序 else ans.append(c); //特殊位置继续放入当前位置 }