Leetcode 38 Count and Say

来源:互联网 发布:mysql 用户管理 编辑:程序博客网 时间:2024/06/05 19:54

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 static String countAndSay(int n) {        String result = "1";        String str="1";        String str_next="";        int count = 1;        for(int i = 0;i< n-1 ;i++){        //System.out.println("i="+i+"str="+str+"str_next="+str_next);                    for(int j =0;j<str.length();j++){                            if(j==str.length()-1){              //  System.out.println("la");                //System.out.println(str_next);                str_next=str_next+count+str.charAt(j);                //System.out.println(str_next);                count = 1;                }                else if(str.charAt(j)==str.charAt(j+1)){                //System.out.println("lala");                    count++;                }                else{                //System.out.println(str.charAt(j));                //System.out.println(str.charAt(j+1));                //System.out.println("count"+count);                    str_next=str_next+count+str.charAt(j);                  //  System.out.println("lalala");                    count = 1;                }            }            result=str_next;            str=str_next;            str_next ="";        }        return result;    }}


0 0