1. 程式人生 > >LeetCode 38. Count and Say 字串“閱讀式”擴張

LeetCode 38. 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.

Subscribe to see which companies asked this question.

public class Solution {
    public String countAndSay(int n) {
        String start = "1";
        for(int i=2;i<=n;i++){
        	char[] mid = start.toCharArray();
        	String result = ""; 
        	int flag = 0;
        	while(flag<mid.length){
        		char k = mid[flag];
        		flag++;
        		int sum = 1;
        		while(flag<mid.length&&mid[flag]==k){
        			sum++;
        			flag++;
        		}
        		result += sum;
        		result += k;
        	}
        	start = result;
        }
        return start;
    }
}