https://leetcode.com/PRoblems/count-and-say/
算法思想:The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...1 is read off as "one 1" or 11.11 is read off as "two 1s" or 21.21 is read off as "one 2, then one 1" or 1211.Given an integer n, generate the nth sequence.Note: The sequence of integers will be represented as a string.
1) 可以根據當前的這個string,來計算下一個string,如“1211”,得到“one 1 one 2 two 1”,即"111221"
程序代碼:public class Solution { public String next(String s) { int length = s.length(); char pre = s.charAt(0); int count = 1; StringBuilder sb = new StringBuilder(); for (int i = 1; i < length; i++) { if (s.charAt(i) == pre) { count++; } else { sb.append(count); sb.append(pre); count = 1; pre = s.charAt(i); } } sb.append(count); sb.append(pre); return sb.toString(); } public String countAndSay(int n) { if (n <= 0) { return ""; } String cas = "1"; for (int i = 2; i <= n; i++) { cas = next(cas); } return cas; }}
新聞熱點
疑難解答