[LeetCode]38. Count and Say

来源:互联网 发布:java method的反射 编辑:程序博客网 时间:2024/05/29 05:03

https://leetcode.com/problems/count-and-say/




要把单独的功能拆分出来。两层循环,外层循环n,内层遍历当前字符串。内层遍历时,计数字符个数,append之后要pos后移。

public class Solution {    public String countAndSay(int n) {        String str = "1";        while (--n > 0) {            str = countAndSay(str);        }        return str;    }    private String countAndSay(String s) {        StringBuilder sb = new StringBuilder();        int pos = 0;        while (pos < s.length()) {            int count = 1;            while (pos < s.length() - 1 && s.charAt(pos) == s.charAt(pos + 1)) {                count++;                pos++;            }            sb.append(count + "" + s.charAt(pos));            pos++;        }        return sb.toString();    }}


0 0