LeetCode刷题答案

比眉伴天荒 2022-04-24 09:46 455阅读 0赞

目录

  1. 无重复字符的最长子串
  1. 寻找两个有序数组的中位数

  2. 最长的回文子串

6.Z 字形变换

  1. 字符串转换整数 (atoi)

    1. 回文数
  2. 盛最多水的容器

  3. 整数转罗马数字

  4. 罗马数字转整数

  5. 最长公共前缀

  6. 三数之和

    1. 最接近的三数之和
  7. 四数之和

    1. 有效的括号
  8. 合并两个有序链表

  9. 删除排序数组中的重复项

  10. 移除元素

  11. 实现 strStr()

  12. 搜索插入位置

    1. 报数
  13. 最大子序和

持续更新中………


3. 无重复字符的最长子串

  1. package cn.zh.t3;
  2. /**
  3. * 无重复字符最长子串
  4. */
  5. public class Test3 {
  6. public static int lengthOfLongestSubstring(String s) {
  7. int l = 0;
  8. int r = 0;
  9. int[] temp = new int[128];
  10. int maxlen = 0;
  11. while(l<s.length()){
  12. if(r<s.length() && temp[s.charAt(r)] == 0){
  13. temp[s.charAt(r)]++;
  14. r++;
  15. }else{
  16. maxlen = Math.max(maxlen,r-l);
  17. temp[s.charAt(l)]--;
  18. l++;
  19. }
  20. }
  21. return maxlen;
  22. }
  23. public static void main(String[] args) {
  24. String string ="abcabcbb";
  25. System.out.println(lengthOfLongestSubstring(string));
  26. // int[] a = new int[344];
  27. // System.out.println(string.charAt(4));
  28. // for(int i = 0 ;i<string.length();i++){
  29. // System.out.println(a[string.charAt(i)]);
  30. //
  31. // }
  32. }
  33. }

4. 寻找两个有序数组的中位数

  1. package cn.zh.t3;
  2. /**
  3. * 最长回文子串
  4. */
  5. public class Test4 {
  6. public static void main(String[] args) {
  7. String s = "a";
  8. System.out.println(longestPalindrome(s));
  9. }
  10. public static String longestPalindrome(String s) {
  11. int max = 0;
  12. int len = s.length();
  13. String test=null;
  14. String ans = null;
  15. for (int i = 0; i < len/2;i++){
  16. for (int j = i+1;j < len;j++){
  17. test = s.substring(i,j);
  18. if (fun(test) && (test.length()>max)){
  19. max = test.length();
  20. ans = s.substring(i,j);
  21. }
  22. }
  23. }
  24. return ans;
  25. }
  26. public static boolean fun(String s){
  27. int len = s.length();
  28. if (s.charAt(0) != s.charAt(len - 1)) {//判断首字符和尾字符是否相等
  29. return false;
  30. }
  31. return true;//首位相等
  32. }
  33. }

5. 最长的回文子串

  1. package cn.zh.t3;
  2. public class Test5 {
  3. public static String longestPalindrome1(String s) {
  4. if (s == null || s.length() == 0) {
  5. return s;
  6. }
  7. String res = "";
  8. boolean[][] dp = new boolean[s.length()][s.length()];
  9. int max = 0;
  10. for (int j = 0; j < s.length(); j++) {
  11. for (int i = 0; i <= j; i++) {
  12. dp[i][j] = s.charAt(i) == s.charAt(j) && ((j - i <= 2) || dp[i + 1][j - 1]);
  13. if (dp[i][j]) {
  14. if (j - i + 1 > max) {
  15. max = j - i + 1;
  16. res = s.substring(i,j + 1);
  17. }
  18. }
  19. }
  20. }
  21. return res;
  22. }
  23. //------------------------------------------
  24. public static String res = "";
  25. public static String longestPalindrome2(String s) {
  26. if (s == null || s.length() == 0) {
  27. return s;
  28. }
  29. for (int i = 0; i < s.length(); i++) {
  30. helper(s,i,i);
  31. helper(s,i,i + 1);
  32. }
  33. return res;
  34. }
  35. public static void helper(String s,int left,int right) {
  36. while (left > 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
  37. left--;
  38. right++;
  39. }
  40. String cur = s.substring(left + 1,right);
  41. if (cur.length() > res.length()) {
  42. res = cur;
  43. }
  44. }
  45. public static void main(String[] args) {
  46. String s = "babad";
  47. System.out.println(longestPalindrome2(s));
  48. }
  49. }

6.Z 字形变换

  1. package cn.zh.t3;
  2. public class Test6 {
  3. public static String convert(String s, int numRows) {
  4. if (numRows == 1) return s;
  5. StringBuilder ret = new StringBuilder();
  6. int n = s.length();
  7. int cycleLen = 2 * numRows - 2;
  8. for (int i = 0; i < numRows; i++) {
  9. for (int j = 0; j + i < n; j += cycleLen) {
  10. ret.append(s.charAt(j + i));
  11. if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
  12. ret.append(s.charAt(j + cycleLen - i));
  13. }
  14. }
  15. return ret.toString();
  16. }
  17. public static void main(String[] args) {
  18. String string = "LEETCODEISHIRING";
  19. int numRows = 3;
  20. System.out.println(convert(string,numRows));
  21. }
  22. }

8. 字符串转换整数 (atoi)

  1. package cn.zh.t3;
  2. /**
  3. * 1.首先去除字符串左右空格,不符合条件的直接return 0;
  4. * 2.sign是符号位,start指针指向第一个数字的位置,如果第一位为数字,则sign=1,start=0,否则firstChar接收字符串第一个字符,若为“+”、“-”,sign分别赋值1、-1,start自增1,
  5. * 3.从字符串第一个为数字的位置开始遍历,res为无符号结果,如果res大于Integer最大值且sign=1,输出Integer的最大值,反之输出Integer最小值,如果遍历到不为数字的字符,则直接返回res*sign;
  6. * 4.如果遍历时该字符串未超范围,且无非数字字符,则返回res * sign;
  7. *
  8. */
  9. public class Test8 {
  10. public static int myAtoi(String str) {
  11. //1.首先去除字符串左右空格,不符合条件的直接return 0;
  12. str=str.trim();
  13. if (str == null || str.length() == 0) {
  14. return 0;
  15. }
  16. int sign = 1;
  17. if(str.charAt(0) == '-'){
  18. sign = -1;
  19. str = str.substring(1);
  20. }else if(str.charAt(0) == '+'){
  21. sign = 1;
  22. str= str.substring(1);
  23. }
  24. long ans = 0;
  25. for(int i = 0; i<str.length();i++) {
  26. char val = str.charAt(i);
  27. if(!Character.isDigit(val))
  28. break;
  29. ans = ans*10 + (val - '0');
  30. if (ans*sign<Integer.MIN_VALUE) return Integer.MIN_VALUE;
  31. if(ans*sign>Integer.MAX_VALUE) return Integer.MAX_VALUE;
  32. }
  33. return (int)ans*sign;
  34. }
  35. public static void main(String[] args) {
  36. String string = "123 4 ee ";
  37. System.out.println(myAtoi(string));
  38. }
  39. }

9. 回文数

  1. package cn.zh.t3;
  2. public class Test9 {
  3. public static boolean isPalindrome(int x) {
  4. int k = x;
  5. int y = 0;
  6. if (x<0){
  7. return false;
  8. }
  9. while (x!=0){
  10. y=y*10+x%10;
  11. x/=10;
  12. }
  13. if (k == y) {
  14. return true;
  15. }else{
  16. return false;
  17. }
  18. }
  19. public static void main(String[] args) {
  20. System.out.println(isPalindrome(12321));
  21. }
  22. }

11. 盛最多水的容器

  1. package cn.zh.t3;
  2. public class Test11 {
  3. public static int maxArea(int[] height) {
  4. int res = 0;
  5. int l = 0, r = height.length - 1;
  6. while (l < r) {
  7. res = Math.max(res,Math.min(height[l],height[r])*(r - l));
  8. if (height[l] < height[r]) {
  9. l++;
  10. }else r--;
  11. }
  12. return res;
  13. }
  14. public static void main(String[] args) {
  15. int[] height = {1,8,6,2,5,4,8,3,7};
  16. System.out.println(maxArea(height));
  17. }
  18. }

12. 整数转罗马数字

  1. package cn.zh.t3;
  2. public class Test12 {
  3. public static String intToRoman(int num) {
  4. int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
  5. String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
  6. StringBuilder sb = new StringBuilder();
  7. for (int i = 0; i < values.length; i++) {
  8. while (num >= values[i]) {
  9. num -= values[i];
  10. sb.append(strs[i]);
  11. }
  12. }
  13. return sb.toString();
  14. }
  15. public static void main(String[] args) {
  16. System.out.println(intToRoman(4));
  17. }
  18. }

13. 罗马数字转整数

  1. package cn.zh.t3;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class Test13 {
  5. public static int romanToInt(String s) {
  6. Map<String,Integer> map = new HashMap<String,Integer>();
  7. map.put("I", 1);
  8. map.put("IV", 4);
  9. map.put("V", 5);
  10. map.put("IX", 9);
  11. map.put("X", 10);
  12. map.put("XL", 40);
  13. map.put("L", 50);
  14. map.put("XC", 90);
  15. map.put("C", 100);
  16. map.put("CD", 400);
  17. map.put("D", 500);
  18. map.put("CM", 900);
  19. map.put("M", 1000);
  20. int ans = 0;
  21. for(int i = 0;i < s.length();) {
  22. if(i + 1 < s.length() && map.containsKey(s.substring(i, i+2))) {
  23. ans += map.get(s.substring(i, i+2));
  24. i += 2;
  25. } else {
  26. ans += map.get(s.substring(i, i+1));
  27. i ++;
  28. }
  29. }
  30. return ans;
  31. }
  32. public static void main(String[] args) {
  33. String s = "MCMXCIV";
  34. System.out.println(romanToInt(s));
  35. }
  36. }

14. 最长公共前缀

  1. package cn.zh.t3;
  2. public class Test14 {
  3. public static String longestCommonPrefix(String[] strs) {
  4. if(strs == null || strs.length == 0) return "";
  5. String res = strs[0];
  6. for (int i = 0; i < strs.length; i++) {
  7. while (strs[i].indexOf(res) != 0 ){
  8. res = res.substring(0,res.length() - 1);
  9. }
  10. }
  11. return res;
  12. }
  13. public static void main(String[] args) {
  14. String[] strs= {"flower","flow","flight"};
  15. String s = longestCommonPrefix(strs);
  16. System.out.println(s);
  17. }
  18. }

15. 三数之和

  1. package cn.zh.t3;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. public class Test15 {
  6. public static List<List<Integer>> threeSum1(int[] nums) {
  7. List<List<Integer>> res = new ArrayList<>();
  8. Arrays.sort(nums);
  9. for (int i = 0; i < nums.length-2; i++) {
  10. if (i > 0 && nums[i] == nums[i - 1]) continue;//去重
  11. int low = i + 1, high = nums.length - 1, sum = 0 - nums[i];
  12. while (low < high) {
  13. if (nums[low] + nums[high] == sum) {
  14. res.add(Arrays.asList(nums[i],nums[low],nums[high]));
  15. while (low < high && nums[low] == nums[low + 1]) low++;//去重
  16. while (low < high && nums[high] == nums[high - 1]) high--;//去重
  17. low++;
  18. high--;
  19. } else if (nums[low] + nums[high] <sum) {
  20. low++;
  21. } else {
  22. high--;
  23. }
  24. }
  25. }
  26. return res;
  27. }
  28. public static List<List<Integer>> threeSum2(int[] nums) {
  29. List<List<Integer>> ans = new ArrayList();
  30. int len = nums.length;
  31. if(nums == null || len < 3) return ans;
  32. Arrays.sort(nums); // 排序
  33. for (int i = 0; i < len ; i++) {
  34. if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
  35. if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
  36. int L = i+1;
  37. int R = len-1;
  38. while(L < R){
  39. int sum = nums[i] + nums[L] + nums[R];
  40. if(sum == 0){
  41. ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
  42. while (L<R && nums[L] == nums[L+1]) L++; // 去重
  43. while (L<R && nums[R] == nums[R-1]) R--; // 去重
  44. L++;
  45. R--;
  46. }
  47. else if (sum < 0) L++;
  48. else if (sum > 0) R--;
  49. }
  50. }
  51. return ans;
  52. }
  53. public static void main(String[] args) {
  54. int[] nums = {-1, 0, 1, 2, -1, -4};
  55. System.out.println(threeSum2(nums));
  56. }
  57. }

16. 最接近的三数之和

  1. package cn.zh.t3;
  2. import java.util.Arrays;
  3. public class Test16 {
  4. public static int threeSumClosest(int[] nums, int target) {
  5. int res = nums[0] + nums[1] + nums[nums.length - 1];
  6. Arrays.sort(nums);
  7. for (int i = 0; i < nums.length; i++) {
  8. int start = i + 1, end = nums.length - 1;
  9. while (start < end) {
  10. int sum = nums[i] + nums[start] + nums[end];
  11. if (sum > target) {
  12. end--;
  13. } else start++;
  14. if (Math.abs(sum - target)<Math.abs(res - target)) {
  15. res = sum;
  16. }
  17. }
  18. }
  19. return res;
  20. }
  21. public static void main(String[] args) {
  22. int[] nums = {-1,2,1,-4};
  23. System.out.println(threeSumClosest(nums,1));
  24. }
  25. }

18. 四数之和

  1. package cn.zh.t3;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. public class Test18 {
  6. public static List<List<Integer>> fourSum(int[] nums, int target) {
  7. List<List<Integer>> res = new ArrayList<>();
  8. if (nums.length < 4) return res;
  9. Arrays.sort(nums);
  10. for (int i = 0; i < nums.length - 3; i++) {
  11. if (i > 0 && nums[i] == nums[i-1]) continue;
  12. for (int j = i + 1; j < nums.length -2; j++) {
  13. if (j > i + 1 && nums[j] == nums[j - 1]) continue;
  14. int low = j + 1, high = nums.length - 1;
  15. while (low < high) {
  16. int sum = nums[i] + nums[j] + nums[low] + nums[high];
  17. if (sum == target) {
  18. res.add(Arrays.asList(nums[i],nums[j],nums[low],nums[high]));
  19. while (low < high && nums[low] == nums[low + 1]) low++;
  20. while (low < high && nums[high] == nums[high - 1]) high--;
  21. low++;
  22. high--;
  23. } else if (sum < target) {
  24. low++;
  25. } else high--;
  26. }
  27. }
  28. }
  29. return res;
  30. }
  31. public static void main(String[] args) {
  32. int[] a = {1,0,-1,0,-2,2};
  33. System.out.println(fourSum(a,0));
  34. }
  35. }

20. 有效的括号

  1. package cn.zh.t3;
  2. import java.util.Stack;
  3. public class Test20 {
  4. public static boolean isValid(String s) {
  5. if (s == null || s.length() == 0) return true;
  6. Stack<Character> stack = new Stack<>();
  7. for (Character ch : s.toCharArray()) {
  8. if (ch == '(') {
  9. stack.push(')');
  10. } else if (ch == '[') {
  11. stack.push(']');
  12. } else if (ch == '{') {
  13. stack.push('}');
  14. } else {
  15. if (stack.isEmpty() || stack.pop() != ch) {
  16. return false;
  17. }
  18. }
  19. }
  20. return stack.isEmpty();
  21. }
  22. public static void main(String[] args) {
  23. String s = "()[]{}";
  24. boolean valid = isValid(s);
  25. System.out.println(valid);
  26. }
  27. }

21. 合并两个有序链表

  1. package cn.zh.t3;
  2. class ListNode {
  3. int val;
  4. ListNode next;
  5. ListNode(int x ){
  6. val = x;
  7. }
  8. }
  9. public class Test21 {
  10. public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
  11. ListNode dummy = new ListNode(0);
  12. ListNode cur = dummy;
  13. while(l1 != null || l2 != null) {
  14. if (l1.val<l2.val) {
  15. cur.next = new ListNode(l1.val);
  16. l1 = l1.next;
  17. } else {
  18. cur.next = new ListNode(l2.val);
  19. l2 = l2.next;
  20. }
  21. cur = cur.next;
  22. }
  23. if (l1!= null) {
  24. cur.next = l1;
  25. } else {
  26. cur.next = l2;
  27. }
  28. return dummy.next;
  29. }
  30. public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
  31. if (l1 == null) {
  32. return l2;
  33. }
  34. if(l2 == null) {
  35. return l1;
  36. }
  37. if (l1.val < l2.val) {
  38. l1.next = mergeTwoLists2(l1.next, l2);
  39. return l1;
  40. } else {
  41. l2.next = mergeTwoLists2(l1, l2.next);
  42. return l2;
  43. }
  44. }
  45. }

26. 删除排序数组中的重复项

  1. package cn.zh.t3;
  2. public class Test26 {
  3. public static int removeDuplicates(int[] nums) {
  4. if (nums == null || nums.length == 0){
  5. return 0;
  6. }
  7. int count = 1;
  8. for (int i = 1; i < nums.length; i++) {
  9. if (nums[i - 1] != nums[i]) {
  10. nums[count++] = nums[i];
  11. }
  12. }
  13. return count;
  14. }
  15. public static void main(String[] args) {
  16. int[] nums = {0,0,1,1,1,2,2,3,3,4};
  17. System.out.println(removeDuplicates(nums));
  18. }
  19. }

27. 移除元素

  1. package cn.zh.t3;
  2. public class Test27 {
  3. public static int removeElement(int[] nums, int val) {
  4. if (nums == null || nums.length == 0)
  5. return 0;
  6. int count = 0;
  7. for (int i = 0; i < nums.length; i++) {
  8. if (nums[i] != val){
  9. nums[count++] = nums[i];
  10. }
  11. }
  12. return count;
  13. }
  14. public static void main(String[] args) {
  15. int[] nums = {0,1,2,2,3,0,4,2};
  16. System.out.println(removeElement(nums,2));
  17. }
  18. }

28. 实现 strStr()

  1. package cn.zh.t3;
  2. public class Test28 {
  3. public static int strStr(String haystack, String needle) {
  4. if (needle == null)
  5. return 0;
  6. for (int i = 0;i <= haystack.length()-needle.length(); i++) {
  7. if (haystack.substring(i,i+needle.length()).equals(needle))
  8. return i;
  9. }
  10. return -1;
  11. }
  12. public static void main(String[] args) {
  13. String h = "hello";
  14. String n = "ll";
  15. System.out.println(strStr(h,n));
  16. }
  17. }

35. 搜索插入位置

  1. package cn.zh.t3;
  2. public class Test35 {
  3. public static int searchInsert(int[] nums, int target) {
  4. int left = 0;
  5. int right = nums.length-1;
  6. while(left <= right) {
  7. int mid = (left + right)/2;
  8. if (nums[mid] == target) {
  9. return mid;
  10. }else if(nums[mid] < target){
  11. left = mid + 1;
  12. }else{
  13. right = mid - 1;
  14. }
  15. }
  16. return left;
  17. }
  18. public static void main(String[] args) {
  19. int nums[] = {1, 2, 4, 5, 7,8, 9};
  20. int target = 3;
  21. System.out.println(searchInsert(nums,target));
  22. }
  23. }

38. 报数

  1. package cn.zh.t3;
  2. public class Test38 {
  3. public static String countAndSay(int n) {
  4. int i = 1;
  5. String res = "1";
  6. while (i < n) {
  7. int count = 0;
  8. StringBuilder sb = new StringBuilder();
  9. char c = res.charAt(0);
  10. for (int j = 0; j < res.length(); j++) {
  11. if (j != res.length() && res.charAt(j) == c) {
  12. count++;
  13. } else {
  14. sb.append(count);
  15. sb.append(c);
  16. if (j != res.length()) {
  17. count = 1;
  18. c = res.charAt(j);
  19. }
  20. }
  21. }
  22. res = sb.toString();
  23. i++;
  24. }
  25. return res;
  26. }
  27. public static void main(String[] args) {
  28. String s = countAndSay(2);
  29. System.out.println(s);
  30. }
  31. }

53. 最大子序和

  1. package cn.zh.t3;
  2. public class Test53 {
  3. public static int maxSubArray(int[] nums) {
  4. int maxSum = nums[0];
  5. int thisSum = 0;
  6. for(int num: nums) {
  7. if(thisSum > 0) {
  8. thisSum += num;
  9. } else {
  10. thisSum = num;
  11. }
  12. maxSum = Math.max(maxSum, thisSum);
  13. }
  14. return maxSum;
  15. }
  16. public static void main(String[] args) {
  17. int[] n = {-2,1,-1,4,};
  18. System.out.println(maxSubArray(n));
  19. }
  20. }

持续更新中………

发表评论

表情:
评论列表 (有 0 条评论,455人围观)

还没有评论,来说两句吧...

相关阅读

    相关 52LeetCode_LeetCode手册

    虽然刷题一直饱受诟病,不过不可否认刷题确实能锻炼我们的编程能力,相信每个认真刷题的人都会有体会。现在提供在线编程评测的平台有很多,比较有名的有 hihocoder,LintCo

    相关 LeetCode指南

    以下是我个人做题过程中的一些体会:  1. LeetCode的题库越来越大,截止到目前,已经有321个问题了。对于大多数人来说,没有时间也没有必要把所有题目都做一遍(时间充

    相关 Leetcode

    39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。