Friday, November 27, 2015

[leetcode] Count and Say

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
    public String countAndSay(int n) {
        String trigger = "1";
        for (int i = 1; i < n; i++){
            trigger = getNumber(trigger);
        }
        
        return trigger;
    }
    
    private String getNumber(String n){
        if (n.equals("")) return "";
        char prev = 'a';
        int count = 0;
        String result = "";
        for (int i = n.length()-1; i >= 0; i--){
            char current = n.charAt(i);
            if (current == prev){
                count++;
            }else{
                if (prev != 'a'){
                    result = ""+count+prev+result;
                }
                prev = current;
                count = 1;
            }
        }
        
        if (prev != 'a' && count > 0){
            result = ""+count+prev+result;
        }
        
        return result;
    }
}

No comments:

Post a Comment