5. 最长回文子串
思想:动态规划
dp[i][j] 表示从 i 到 j 是否为回文子串。
dp[i][j] = (s[i] == s[j]) && dp[i + 1][j - 1], 即判断s[i]和s[j]是否相等,相等判断i+1到j-1是否为回文子串,若是则 i 到 j 也是回文子串。
代码实现
import java.util.*; public class Solution { public String longestPalindrome(String s) { int n = s.length(); boolean[][]dp = new boolean[n][n]; for (int i = 1; i < n; i++) { dp[i][i] = true; dp[i][i-1] = true; } dp[0][0] = true; int posx = 0, posy = 0, max = 0; for (int j = 1; j < n; j++) { for (int i = 0; i < j ; i++) { if(dp[i+1][j-1] && s.charAt(i) == s.charAt(j)){ dp[i][j] = true; if (Math.abs(i-j) + 1 > max){ max = Math.abs(i-j) + 1; posx = i; posy = j; } } else dp[i][j] = false; } } return s.substring(posx, posy + 1); } public static void main(String[] args) { Solution s = new Solution(); Scanner in = new Scanner(System.in); System.out.println(s.longestPalindrome("cbbd")); } }
6. Z 字形变换
思路:
public String convert(String s, int numRows) { if(s.length() <= 2) return s; if(numRows == 1) return s; // List<StringBuffer> list = new ArrayList<>(); StringBuffer[] stb = new StringBuffer[numRows]; for (int i = 0; i < numRows; i++) { stb[i] = new StringBuffer(); } int i = 0, flag = -1; for (char op : s.toCharArray()) { stb[i].append(op); if(i == 0 || numRows - 1 == i) flag = -flag; i += flag; } StringBuffer res = new StringBuffer(); for (int j = 0; j < numRows; j++) { res.append(stb[j]); } return new String(res); }