classSolution{ public String countAndSay(int n){ String[] dp = new String[n+1]; dp[1] = "1"; // 动归 for (int i = 2; i <= n; i++) dp[i] = helper(dp[i - 1]); return dp[n]; }
private String helper(String s){ StringBuilder sb = new StringBuilder(); // 遍历处理上一个字符串 int length = s.length(); for (int i = 0; i < length;) { char c = s.charAt(i); int count = 0; while (i < length && c == s.charAt(i)){ count++; i++; } sb.append(count).append(c); } return sb.toString(); } }