外观数列 (Count and Say)

 

思路:

// @Title: 外观数列 (Count and Say)
// @Author: qisiii
// @Date: 2024-06-13 18:42:28
// @Runtime: 1 ms
// @Memory: 40.5 MB
// @comment: 
// @flag: 
class Solution {
    public String countAndSay(int n) {
        int start=1;
        String res=null;
        while(start<=n){
            if(start==1){
                res="1";
            }else{
                res=code(res);
            }
            start++;
        }
        return res;
    }

    public String code(String string){
        char[] chars=string.toCharArray();
        StringBuilder str=new StringBuilder();
        char old=chars[0];int count=1;
        for(int i=1;i<string.length();i++){
            if(old!=chars[i]){
                str.append(count);
                str.append(old);
                count=0;
            }
            count++;
            old=chars[i];
        }
        if(count!=0){
            str.append(count);
            str.append(old);
        }
        return str.toString();
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18