38. Count and Say

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }

}

以上是关于38. Count and Say的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode38. Count and Say

38. Count and Say - Unsolved

leetcode 38 Count and Say

38. Count and Say

38. Count and Say

38. Count and Say [easy] (Python)