字符整数化
String str = s; int len = str.length(); // str.charAt(i) 方法回去检查下标的合法性,一般先转换成字符数组 char[] charArray = str.toCharArray();
// 1、去除前导空格int index = 0;while (index < len && charArray[index] == ' ') {index++;}// 2、如果已经遍历完成(针对极端用例 " ")if (index == len) {return 0;}// 3、如果出现符号字符,仅第 1 个有效,并记录正负int sign = 1;char firstChar = charArray[index];if (firstChar == '+') {index++;} else if (firstChar == '-') {index++;sign = -1;}// 4、将后续出现的数字字符进行转换// 不能使用 long 类型,这是题目说的int res = 0;while (index < len) {char currChar = charArray[index];// 4.1 先判断不合法的情况if (currChar > '9' || currChar < '0') {break;}// 题目中说:环境只能存储 32 位大小的有符号整数,因此,需要提前判:断乘以 10 以后是否越界if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {return Integer.MAX_VALUE;}if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {return Integer.MIN_VALUE;}// 4.2 合法的情况下,才考虑转换,每一步都把符号位乘进去res = res * 10 + sign * (currChar - '0');index++;}return res;
求容器最大容量
int i = 0, j = height.length - 1, res = 0;while(i < j){res = height[i] < height[j] ?Math.max(res, (j - i) * height[i++]):Math.max(res, (j - i) * height[j--]);}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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
