2014年2月17日星期一

LeetCode - Count and Say

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.

 public class Solution {
    public String countAndSay(int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        String num = "1";
        if(n==1) {
            return num;
        }
        for(int i=1;i<n;i++) {
            num = say(num);
        }
        return num;
    }
 
    public String say(String n) {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<n.length();) {
            char num = n.charAt(i);
            int count = 1;
            if(i!=n.length()-1 && num==n.charAt(i+1)) {
                i++;
                while(i<n.length()) {
                    if(num!=n.charAt(i)) {
                        break;
                    }
                    i++;
                    count++;
                }
            } else {
                i++;
            }
            sb.append(count).append(num);
        }
        return sb.toString();
    }
}

public class Solution {
    public String countAndSay(int n) {
        int k = 1;
        String str = "1";
        while(k<n) {
            str = help(str);
            k++;
        }
        return str;
    }
   
    public String help(String str) {
        StringBuilder sb = new StringBuilder();
        int count = 1;
        char pc = str.charAt(0);
        for(int i=1;i<str.length();i++) {
            if(str.charAt(i)==str.charAt(i-1)) {
                count += 1;
            } else {
                sb.append(count).append(str.charAt(i-1));
                count = 1;
            }
        }
        sb.append(count).append(str.charAt(str.length()-1));
        return sb.toString();
    }
}

没有评论:

发表评论