Java Solution 4ms beats 94%


  • 1
    M
    public class Solution {
        public String countAndSay(int n) {
            
            StringBuilder curr = new StringBuilder();
            StringBuilder prev = new StringBuilder();
            
            if(n<=0) return curr.toString();
            curr.append(1);
            
            for(int i = n; i>1; i--) {
            	
                prev = curr;
                curr = new StringBuilder();
                
                char[] c = prev.toString().toCharArray();
                int count = 1;
                
                for(int j = 1; j <=c.length; j++) {
                    
                	if(j == c.length || c[j]!=c[j-1]) {
                        curr.append(count);
                        curr.append(c[j-1]);
                        count = 1 ;
                    } else {
                        count++;
                    }
                    
                }
                
            }
            
            return curr.toString();
        }
        
    }
    

Log in to reply
 

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