My Accepted Java Solution (4ms)


  • 0
    G
    public class Solution {
        public String countAndSay(int n) {
            StringBuilder seq = new StringBuilder("1");
            for(int i=1;i<n;i++){
                seq = getNextSeq(seq);
            }
            return seq.toString();
        }
        
        public StringBuilder getNextSeq(StringBuilder s){
            int count = 1;
            int sLen = s.length();
            StringBuilder res = new StringBuilder("");
            for(int i=1;i<sLen;i++){
                if(s.charAt(i)==s.charAt(i-1)){
                    count++;
                } else {
                    res.append(count);
                    res.append(s.charAt(i-1));
                    count = 1;
                }
            }
            res.append(count);
            res.append(s.charAt(sLen-1));
            return res;
        }
    }
    

  • 0
    N

    Same thought, but why my solution took 30ms?!!!

    public class Solution {
        public String countAndSay(int n) {
            String prev="1";
            if(n==1) return prev;
            String result="";
    
            for(int i=1;i<n;i++){
                result="";
                int count=1;
                for(int j=0;j<prev.length()-1;j++){
                    if(prev.charAt(j)!=prev.charAt(j+1)){
                        result=result+count+prev.charAt(j);
                        count=1;
                    }else{
                        count++;
                    }
                }
                result=result+count+prev.charAt(prev.length()-1);
                prev=result;
                
            }
            return result;
        }
    }
    

  • 0
    G

    @ns_1121 You need to use StringBuilder instead of String for better performance! Regular Strings operations are very slow as every time it creates new String.


Log in to reply
 

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