TypechoJoeTheme

IT技术分享

统计

[LeetCode 38] Count and Say[Java]

2018-01-05
/
0 评论
/
805 阅读
/
正在检测是否收录...
01/05

1. Description

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.

Note

Each term of the sequence of integers will be represented as a string.

2. Example

[tabby title="Example 1"]

Input: 1
Output: "1"

[tabby title="Example 2"]

Input: 4
Output: "1211"

[tabbyending]

3. Code

public class LeetCode0038 {
    public String countAndSay(int n) {
        if (n < 1) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        String str = "1";
        for (int i = 2; i <= n; i++) {
            char pre = str.charAt(0);
            int count = 1;
            for (int j = 1; j < str.length(); j++) {
                char c = str.charAt(j);
                if (c != pre) {
                    sb.append(count).append(pre);
                    count = 1;
                    pre = c;
                } else {
                    count++;
                }
            }
            sb.append(count).append(pre);
            str = sb.toString();
            sb.setLength(0);
        }
        return str;
    }

    public static void main(String[] args) {
        LeetCode0038 leetcode = new LeetCode0038();
        System.out.println(leetcode.countAndSay(5));
    }
}
String
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1366/(转载时请注明本文出处及文章链接)