My while loop solution


  • 0
    X
    public class Solution {
        public String countAndSay(int n) {
            String s = "1";
            while(n-->1){
                StringBuilder sb = new StringBuilder();
                int count = 0;
                char c = s.charAt(0);
                while(!s.isEmpty()){
                    if(c == s.charAt(0))
                        count++;
                    else{
                        sb.append(count);
                        sb.append(c);
                        count = 1;
                        c = s.charAt(0);
                    }
                    s = s.substring(1);
                    if(s.isEmpty()){
                        sb.append(count);
                        sb.append(c);
                    }
                }
                s = sb.toString();
            }
            return s;
        }
    }
    

Log in to reply
 

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