38. Count and Say

原题链接:https://leetcode.com/problems/count-and-say/description/
奶奶的,这道题本身题意都不好读懂,然后即使明白了也还是没有写出解答来,所以最后还是无耻的抄袭了讨论区的答案!
首先要读懂题意:https://www.2cto.com/kf/201507/416783.html
然后是解答:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) throws InterruptedException {
        Solution s = new Solution();
        System.out.println(s.countAndSay(6)); // 312211
    }

    public String countAndSay(int n) {
        String s = "1";
        for (int i = 1; i < n; i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 1, count = 1; j <= s.length(); j++) {
                if (j == s.length() || s.charAt(j - 1) != s.charAt(j)) {
                    sb.append(count);
                    sb.append(s.charAt(j - 1));
                    count = 1;
                } else {
                    count++;
                }
            }
            s = sb.toString();
        }
        return s;
    }

}
posted @ 2018-03-15 11:40  optor  阅读(105)  评论(0编辑  收藏  举报