package cn.dcs.leef.leetcode;


public class CountAndSay {
	public static String countAndSay(int n) {
		String res="1";
		while(--n>0){
			StringBuilder builder=new StringBuilder();
			String str=res;
			char pre=str.charAt(0);int count=1;
			char p = pre;
			for(int i=1;i<str.length();i++){
				p=str.charAt(i);
				if(p==pre){
					count++;
				}else {
					builder.append(count+""+pre);
					count=1;
					pre=p;
				}
			}
			builder.append(count+""+p);
			res=builder.toString();
		}
		return res;
    }
	
	public static void main(String []args){
		System.out.println(countAndSay(5));
	}
	
	
	public static String countAndSay1(int n) {
		//³ä·ÖÀí½âÌâÄ¿ÒâË¼×ö´ð£¬Á½²ãÑ­»·£¬nÖ»ÓÃÀ´¼ÆÊý
        String res = "1";
        while (--n > 0) {
            StringBuilder sb = new StringBuilder();
            char[] prev = res.toCharArray();
            //ÓÃ´Ë·½·¨½ÏºÃÐ©
            for (int i = 0; i < prev.length; i++) {
                int count = 1; // initialize current count as 1
                while (i + 1 < prev.length && prev[i] == prev[i + 1]) {
                    count++; // search for same char
                    i++;
                }
                sb.append(count).append(prev[i]);
            }
            res = sb.toString();
        }
        return res;
    }
}
