Count and Say, Leetcode 解题笔记

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.

关于String的实现题,算法没什么窍门。

public class Solution {
    public String countAndSay(int n) {
        int count = 0;
        boolean same = false;
        if(n==0) return "";
        if(n==1) return "1";
        if(n==2) return "11";
        StringBuilder cur = new StringBuilder("11");
        
        int i = 0;
        while(i < n-1){
            StringBuilder temp = new StringBuilder();
            for(int j = 1; j < cur.length(); j++){
                if(cur.charAt(j) != cur.charAt(j-1)){
                    temp.append(Integer.toString(count));
                    temp.append(cur.charAt(j-1));
                    count = 1;
                    same = false;
                }
                else{
                    count++;
                    same = true;
                }
                if(j == cur.length()-1){
                    if(same){
                        temp.append(Integer.toString(count));
                    }
                    else{
                        temp.append("1");
                    }
                    temp.append(cur.charAt(j));
                }
            }
            count = 1;
            cur = new StringBuilder(temp);
            i++;
        }
        return cur.toString();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s