字符整数化

String str = s; int len = str.length(); // str.charAt(i) 方法回去检查下标的合法性,一般先转换成字符数组 char[] charArray = str.toCharArray();

  1. // 1、去除前导空格
  2. int index = 0;
  3. while (index < len && charArray[index] == ' ') {
  4. index++;
  5. }
  6. // 2、如果已经遍历完成(针对极端用例 " ")
  7. if (index == len) {
  8. return 0;
  9. }
  10. // 3、如果出现符号字符,仅第 1 个有效,并记录正负
  11. int sign = 1;
  12. char firstChar = charArray[index];
  13. if (firstChar == '+') {
  14. index++;
  15. } else if (firstChar == '-') {
  16. index++;
  17. sign = -1;
  18. }
  19. // 4、将后续出现的数字字符进行转换
  20. // 不能使用 long 类型,这是题目说的
  21. int res = 0;
  22. while (index < len) {
  23. char currChar = charArray[index];
  24. // 4.1 先判断不合法的情况
  25. if (currChar > '9' || currChar < '0') {
  26. break;
  27. }
  28. // 题目中说:环境只能存储 32 位大小的有符号整数,因此,需要提前判:断乘以 10 以后是否越界
  29. if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
  30. return Integer.MAX_VALUE;
  31. }
  32. if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {
  33. return Integer.MIN_VALUE;
  34. }
  35. // 4.2 合法的情况下,才考虑转换,每一步都把符号位乘进去
  36. res = res * 10 + sign * (currChar - '0');
  37. index++;
  38. }
  39. return res;

求容器最大容量

  1. int i = 0, j = height.length - 1, res = 0;
  2. while(i < j){
  3. res = height[i] < height[j] ?
  4. Math.max(res, (j - i) * height[i++]):
  5. Math.max(res, (j - i) * height[j--]);
  6. }
  7. return res;

作者:jyd
链接:https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

最长回文子串

int n = s.length();
boolean[][] dp = new boolean[n][n];
String ans = “”;
for (int l = 0; l < n; ++l) {
for (int i = 0; i + l < n; ++i) {
int j = i + l;
if (l == 0) {
dp[i][j] = true;
} else if (l == 1) {
dp[i][j] = (s.charAt(i) == s.charAt(j));
} else {
dp[i][j] = (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]);
}
if (dp[i][j] && l + 1 > ans.length()) {
ans = s.substring(i, i + l + 1);
}
}
}
return ans;
执行用时:346 ms, 在所有 Java 提交中击败了24.94%的用户
内存消耗:44.3 MB, 在所有 Java 提交中击败了17.98%的用户
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。