Very easy-to-understand Java code


  • 0
    J
    public class Solution {
        public String countAndSay(int n) {
            if(n==0) return "";
            if(n==1) return "1";
            String res="1";
            for(int i=1;i<n;i++){
                res=build(res);
            }
            return res;
        }
        public String build(String str){
            if(str.length()==0||str==null) return "";
            if(str.length()==1) return "1"+str;
            StringBuilder sb=new StringBuilder("");
            int count=1;
            for(int i=1;i<str.length();i++){
                if(str.charAt(i-1)==str.charAt(i)){//count the same character
                    count++;
                }else{//add the same characters before str[i] to sb
                    sb.append(count);
                    sb.append(str.charAt(i-1));
                    count=1;
                }
                if(i==str.length()-1) {//if str[i] is the last, add count+str[i] to the sb
                    sb.append(count);
                    sb.append(str.charAt(i));
                }
            }
            return sb.toString();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.