刷题记录
入门
1. 输入处理(重要):HJ5 进制转换
java"> public static void main(String[] args) {Scanner in = new Scanner(System.in);String str = in.nextLine().replaceAll("0[xX]","");System.out.print(Integer.parseInt(str,16));}
2. 排列组合:(牛客搜索)NC61.两数之和
暴力解法:
java">class Solution {public int[] twoSum(int[] nums, int target) {for(int i = 0;i<nums.length-1; i++){for(int j = i+1;j<nums.length;j++){if(nums[i]+nums[j]==target){return new int[]{i, j}; }}}return null;}}
改进:
java">class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer,Integer> map = new HashMap<>();for(int i = 0;i<nums.length; i++){int val = target-nums[i];if(map.containsKey(val)){return new int[]{i,map.get(val)};}map.put(nums[i],i);}return null;}}
3. 快速排序:HJ3.明明的随机数
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);in.nextInt();Set<Integer> numbers = new TreeSet<>(); while (in.hasNextInt()){numbers.add(in.nextInt());}for(Integer num : numbers){System.out.println(num); }}
}
4. 哈希表:HJ10.字符个数统计
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);String str = in.nextLine();Set<Character> set = new HashSet<>();for(int i = 0;i<str.length();i++){char s = str.charAt(i);if(s<=0 || s>= 127 || s == '\n'){continue;}set.add(s); }System.out.print(set.size());}
}
5. 递归:NC68.跳台阶
java">import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param number int整型 * @return int整型*/public int jumpFloor (int number) {// write code hereif(number <= 1){return 1;}return jumpFloor(number-1) + jumpFloor(number-2);}
}
字符串操作
1. HJ17.坐标移动
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);String[] strs = in.nextLine().split(";");Set<String> set = new HashSet<>();set.add("A");set.add("S");set.add("W");set.add("D");int resultX = 0;int resultY = 0;for (String str : strs) {if (str.length() < 2) {continue;}String direction = str.substring(0, 1);String num = str.substring(1);if (str.length() > 1 && str.length() <= 3 && set.contains(direction) &&num.matches("\\d+")) {switch (direction) {case "A":resultX -= Integer.parseInt(num);break;case "D":resultX += Integer.parseInt(num);break;case "W":resultY += Integer.parseInt(num);break;case "S":resultY -= Integer.parseInt(num);break;}}}System.out.print(Integer.toString(resultX) + "," + Integer.toString(resultY));}
}
改进:
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);String[] strs = in.nextLine().split(";");int resultX = 0;int resultY = 0;for (String str : strs) {if (str.length() < 2 || str.length() > 3 || !str.matches("^[AWSD]\\d+$")) {continue;}char direction = str.charAt(0);int num = Integer.parseInt(str.substring(1));switch (direction) {case 'A':resultX -= num;break;case 'D':resultX += num;break;case 'W':resultY += num;break;case 'S':resultY -= num;break;}}System.out.print(Integer.toString(resultX) + "," + Integer.toString(resultY));}
}
2. HJ20.密码验证合格程序
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);Boolean flag = false;while (in.hasNext()) {String str = in.nextLine();if (str.length() > 8) {Set<Integer> set = new HashSet<>();for (int i = 0 ; i < str.length(); i++) {char s = str.charAt(i);if (Character.isDigit(s)) {set.add(1);} else if (Character.isUpperCase(s)) {set.add(2);} else if (Character.isLowerCase(s)) {set.add(3);} else if (!Character.isLetterOrDigit(s)) {set.add(4);}}if (set.size() > 2) {flag = verify(str);}}String result = flag ? "OK" : "NG";System.out.println(result);}}public static boolean verify(String str) {for (int i = 0 ; i < str.length() - 3; i++) {String sonStr = str.substring(i, i + 3);int count = 0;for (int j = i ; j < str.length() - 3; j++) {String otherStr = str.substring(j, j + 3); if (sonStr.equals(otherStr)) { count++;} }if(count >1 ){return false;}}return true;}
}
3. HJ23.删除字符串中出现次数最少的字符
java">import java.util.*;
import java.util.stream.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);String str = in.next();Map<Character, Integer> map = new HashMap<>();for (int i = 0; i < str.length(); i++) {Character item = str.charAt(i);map.put(item, map.getOrDefault(item, 0) + 1);};List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());list.sort(Map.Entry.comparingByValue());Integer minCount = list.get(0).getValue();Set<Character> toRemove = list.stream().filter(data -> data.getValue() ==minCount).map(Map.Entry::getKey).collect(Collectors.toSet());for(Character c : toRemove){str = str.replaceAll(c.toString(),"");}System.out.print(str);}
}
4. HJ33.整数与IP地址间的转换
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);List<String> list = new ArrayList<>();StringBuilder sb ;String numTwo;StringBuilder numTwoResult = new StringBuilder();while (in.hasNext()){list.add(in.next());}for(String ipStr : list.get(0).split("\\.")){numTwo = Integer.toBinaryString(Integer.parseInt(ipStr));sb = new StringBuilder(numTwo);while(sb.length()<8){sb.insert(0,'0');}numTwoResult.append(sb);}System.out.println(toTen(numTwoResult.toString()));StringBuilder tenToTwoSb = new StringBuilder(Long.toBinaryString(Long.parseLong(list.get(1))));while(tenToTwoSb.length()<32){tenToTwoSb.insert(0,'0');}StringBuilder numTenResult = new StringBuilder();for(int i = 0;i<tenToTwoSb.length();i+=8){numTenResult.append(toTen(tenToTwoSb.substring(i,i+8))+".");}System.out.println(numTenResult.substring(0,numTenResult.length()-1));}public static String toTen(String numTwoResult){Long result = 0L ;Long base =1L;for(int i = numTwoResult.length()-1;i>=0;i--){if(numTwoResult.charAt(i) == '1'){result += base;}base *= 2;}return String.valueOf(result);}
}
注意使用long,int会超出范围
5. HJ101.输入整型数组和排序标识
java">import java.util.*;
import java.util.stream.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);List<String> list = new ArrayList<>();while (in.hasNext()) {list.add(in.nextLine());}List<String> numList = Arrays.asList(list.get(1).split(" "));if (list.get(2).equals("0")) {Collections.sort(numList, (a, b)->Integer.compare(Integer.parseInt(a),Integer.parseInt(b)));} else {Collections.sort(numList, (a, b)->Integer.compare(Integer.parseInt(b),Integer.parseInt(a)));}System.out.print(String.join(" ", numList)) ;}
}
改进:直接用数组
java">import java.util.*;
import java.util.stream.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);int length = in.nextInt();int[] arr = new int[length];for(int i = 0; i<length;i++){arr[i] = in.nextInt();}Arrays.sort(arr);if(in.nextInt()==0){for(int i=0;i<length;i++){System.out.print(arr[i]+" ");}}else{for(int i=length-1;i>=0;i--){System.out.print(arr[i]+" ");}}}
}
6. HJ106.字符串逆序
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i = str.length()-1;i>=0;i–){
System.out.print(str.charAt(i));
}
}
}
···
其它:
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);StringBuilder str = new StringBuilder(in.nextLine());System.out.print(str.reverse());}
}
排序
1. HJ8.合并表记录
java">import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);Map<Integer,Integer> map = new TreeMap<>();int length = Integer.parseInt( in.nextLine());for(int i = 0 ; i< length;i++){String[] str = in.nextLine().split(" ");int key = Integer.parseInt(str[0]);int value = Integer.parseInt(str[1]);if(map.containsKey(key)){value += map.get(key);}map.put(key,value);}for(Map.Entry<Integer,Integer> item : map.entrySet()){System.out.println(item.getKey() + " " + item.getValue());}}
}
2. HJ14.字符串排序
java">import java.util.*;
import java.util.stream.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);int length = Integer.parseInt( in.nextLine());List<String> list = new ArrayList<>();while(in.hasNextLine()){list.add(in.nextLine());}Collections.sort(list);for(String str : list){System.out.println(str);}}
}
3. HJ27.查找兄弟单词
java">import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);List<String> list = Arrays.asList(in.nextLine().split(" "));int length = Integer.parseInt(list.get(0));String base = list.get(list.size() - 2);char[] newBase = base.toCharArray();Arrays.sort(newBase);int baseLength = base.length();int k = Integer.parseInt(list.get(list.size() - 1));List<String> broList = new ArrayList<>();for (int j = 1; j < list.size() - 2; j++) {boolean flag = true;if (list.get(j).length() != baseLength || list.get(j).equals(base)) {flag = false;continue;} else {char[] newStr = list.get(j).toCharArray();Arrays.sort(newStr);if (!String.valueOf(newStr).equals(String.valueOf(newBase))) {flag = false;continue;}}for (int i = 0; i < base.length(); i++) {if (!list.get(j).contains(String.valueOf( base.charAt(i)))) {flag = false;break;}}if (flag) {broList.add(list.get(j));}}System.out.println(broList.size());Collections.sort(broList);if (broList != null && broList.size()>=k) {System.out.println(broList.get(k - 1));}}
}
4. NC37.合并区间
java">import java.util.*;/** public class Interval {* int start;* int end;* public Interval(int start, int end) {* this.start = start;* this.end = end;* }* }*/public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param intervals Interval类ArrayList* @return Interval类ArrayList*/public int min = 0;public int max = 0;public ArrayList<Interval> merge (ArrayList<Interval> intervals) {// write code hereif(intervals==null || intervals.isEmpty() || intervals.size()==1){return intervals;}Collections.sort(intervals,(a,b)->(Integer.compare(a.start,b.start)));ArrayList<Interval> list = new ArrayList<>(); for (int i = 0; i < intervals.size(); i ++) {Interval current = intervals.get(i);if(list.isEmpty()||current.start>list.get(list.size()-1).end){list.add(current); }else{list.get(list.size()-1).end = Math.max(list.get(list.size()-1).end, current.end);} }return list;}}
5.(较难)HJ68.成绩排序
java"> import java.util.*;
import java.util.stream.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);while (in.hasNextLine()) {int number = Integer.parseInt(in.nextLine());String sort = in.nextLine();Student[] students = new Student[number];for (int i = 0; i < number; i++) {String line = in.nextLine();String[] split = line.split(" ");students[i] = new Student(split[0], Integer.parseInt(split[1]));}Arrays.sort(students, (o1, o2) -> {if (sort.equals("0")) {return o2.score - o1.score;} else {return o1.score - o2.score;}});for (Student student : students) {System.out.println(student.name + " " + student.score);}}}public static class Student {String name;int score;public Student(String name, int score) {this.name = name;this.score = score;}}
}
栈
1. NC52.括号序列
java">import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param s string字符串 * @return bool布尔型*/public boolean isValid (String s) {// write code hereStack<Character> stack = new Stack<>();for(int i=0;i<s.length();i++){if(s.charAt(i) == '('){stack.push(')');}else if(s.charAt(i) == '['){stack.push(']');}else if(s.charAt(i) == '{'){stack.push('}');}else if(stack.isEmpty() || stack.pop() != (s.charAt(i))){return false;}}return stack.isEmpty();}
}
2. leetcode 1614.括号的最大嵌套深度
https://leetcode.cn/problems/maximum-nesting-depth-of-the-parentheses/
java">class Solution {public int maxDepth(String s) {int result = 0;int count = 0;Stack<Character> stack = new Stack<>();for(int i = 0 ; i < s.length();i++){if(s.charAt(i)=='('){result++;stack.push(')');}else if(s.charAt(i)==')'){stack.pop();count = count<result?result:count;result--;}}return count;}
}
改进:
java">class Solution {public int maxDepth(String s) {int result = 0;int count = 0;for(int i = 0 ; i < s.length();i++){if(s.charAt(i)=='('){result++; }else if(s.charAt(i)==')'){ count = count<result?result:count;result--;}}return count;}
}
排列组合
1. 面试题 08.07. 无重复字符串的排列组合面试题 (回朔法-中等)
https://leetcode.cn/problems/permutation-i-lcci/description/
回朔算法 固定模版 直接套用
java">class Solution {public String[] permutation(String S) {boolean[] flag = new boolean[S.length()];List<String> res = new ArrayList<>();trackback(S,flag,new StringBuilder(),res);String[] strs = new String[res.size()];for(int i=0;i<res.size();i++){strs[i] = res.get(i);}return strs;}public void trackback(String S,boolean[] flag,StringBuilder stringBuilder, List<String> res){if(stringBuilder.length()==S.length()){res.add(stringBuilder.toString());return;}for(int i=0;i<S.length();i++){if(flag[i]==false){stringBuilder.append(S.charAt(i));flag[i]=true;trackback(S,flag,stringBuilder,res);stringBuilder.deleteCharAt(stringBuilder.length()-1);flag[i] = false;}}}
}
2. 面试题08.08.有重复字符串的排列组合(中等)
java">class Solution {int length = 0;public String[] permutation(String S) {char[] base = S.toCharArray();Arrays.sort(base);length = S.length();boolean[] flags = new boolean[S.length()];List<String> res = new ArrayList<>();trackBack(base,flags,new StringBuilder(),res);return res.toArray(new String[res.size()]);}public void trackBack(char[] base,boolean[] flags,StringBuilder stringBuilder,List<String> res){if(stringBuilder.length() == length){res.add(stringBuilder.toString());return;}for(int i =0;i<length;i++){if(flags[i]==true || (i>0 && base[i] == base[i-1]) && !flags[i-1]){continue;}stringBuilder.append(base[i]);flags[i] = true;trackBack(base,flags,stringBuilder,res);stringBuilder.deleteCharAt(stringBuilder.length()-1);flags[i] = false;}}
}
3. 77.组合(中等)
https://leetcode.cn/problems/combinations/description/
java">class Solution {List<List<Integer>> resultList = new ArrayList<>();public List<List<Integer>> combine(int n, int k) {trackBack(n, k, new ArrayList<Integer>(), 1);return resultList;}public void trackBack(int n,int k, List<Integer> list, int index){if(list.size() == k){resultList.add(new ArrayList<>(list));return;}for (int i = index; i <= n; i++) {list.add(i);trackBack(n , k, list, i + 1);list.remove(list.size() - 1);}}
}
双指针
1.leetcode 674.最长连续递增序列
java">class Solution {public int findLengthOfLCIS(int[] nums) {int result = 1 ;int count = 1 ;for(int i=1;i<nums.length;i++){if (nums[i] > nums[i - 1]){count++;}else{result = Math.max( result , count);count = 1;}}return Math.max( result , count);}
}
NC17.最长回文子串(动态规划 || 中心扩展 -中等)
动态规划的理解可以看here
java">
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param A string字符串* @return int整型*/public int getLongestPalindrome (String A) {int max = 1;int length = A.length();boolean[][] dp = new boolean[length][length];for(int i =0;i<length;i++){dp[i][i] = true;}for(int j=1;j<length;j++){for(int i=0;i<j;i++){if(A.charAt(i) != A.charAt(j)){dp[i][j] = false;}else{dp[i][j] = j-i<3||dp[i+1][j-1];}if(dp[i][j]){max=Math.max(max,j-i+1);}}}return max;}
}
- 中心扩展
java">import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param A string字符串* @return int整型*/public int getLongestPalindrome (String A) {int max = 0;int lengthA = A.length();for (int i = 0; i < lengthA; ) {int begin = i;int end = i;while (end < lengthA - 1 && A.charAt(end) == A.charAt(end + 1)) {end++;}i = end + 1;while (begin > 0 && end < lengthA - 1 &&A.charAt(begin - 1) == A.charAt(end + 1)) {begin--;end++;}max = Math.max(max, end - begin + 1);}return max;}
}