Best java solution


  • 0
    M
    public String countAndSay(int n) {
            if(n == 0) return "";
            if(n == 1) return "1";
            String s = "1";
            for (int i = 1; i < n; i++) {
                s = getString(s);
            }
            return s;
        }
    
        private String getString(String s) {
            StringBuilder s2 = new StringBuilder();
            int sameCharCount=0;
            char prevChar = 'a';
            for(char ch : s.toCharArray())
            {
                if(prevChar == 'a') prevChar=ch;
                if(ch == prevChar) sameCharCount++;
                else {
                    s2.append(Integer.toString(sameCharCount) + prevChar);
                    prevChar=ch;
                    sameCharCount=1;
                }
            }
            s2.append(Integer.toString(sameCharCount) + prevChar);
            return s2.toString();
        }
    

Log in to reply
 

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