《剑指offer》相关题目
这几道题目比较简单,算是入门题目
LeetCode 相关题目
题解参考:买卖股票的最佳时机 系列(Java)
题目链接:5. 最长回文子串
class Solution {
public String longestPalindrome(String s) {
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;
}
}
题目链接:53. 最大子序和
class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0];
int last = nums[0];
for (int i = 1; i < nums.length; i++) {
int curDp = last > 0 ? last + nums[i] : nums[i];
last = curDp;
max = Math.max(curDp, max);
}
return max;
}
}
题目链接:62. 不同路径
class Solution {
public int uniquePaths(int m, int n) {
int[][] f = new int[m][n];
for (int i = 0; i < m; ++i) {
f[i][0] = 1;
}
for (int j = 0; j < n; ++j) {
f[0][j] = 1;
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
f[i][j] = f[i - 1][j] + f[i][j - 1];
}
}
return f[m - 1][n - 1];
}
}