38. Count and Say

来源:互联网 发布:淘宝网争议处理规则 编辑:程序博客网 时间:2024/06/15 18:47

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) {        String previous = "11";        if(n == 1){            return "1";        }        if(n == 2){            return "11";        }        StringBuffer result = new StringBuffer();        for(int i=3; i<=n; i++){            result.delete(0, result.length()); //每次读进来一个新的buffer            int count = 1;            for(int j=1; j<previous.length(); j++){                if(previous.charAt(j) == previous.charAt(j-1)){                    count++;                }else{                    result.append(count);                    result.append(previous.charAt(j-1));                    count = 1; //只有在加完之后才把count置位1                }                if(j==previous.length() - 1){ //因为之前都是加的j-1,所以要把最后一个元素加进去                result.append(count);                    result.append(previous.charAt(previous.length() -1));                }            }            previous = result.toString();        }        return result.toString();    }}


原创粉丝点击