Java solution beating 97% of the submissions


  • 0
    L

    A simple Java solution that LeetCode thinks is better than quite a few of them :).

    public class Solution {
        public String countAndSay(int n){
          String start="1";
          for(int i=2;i<=n;i++) {
              start = getNext(start);
          }
          
          return start;
        }
        
        private String getNext(String str) {
          StringBuilder builder = new StringBuilder();
          int count=1;
          for(int i=1;i<=str.length();i++) {
              if(str.length()==i || str.charAt(i)!=str.charAt(i-1)) {
                  builder.append(count);
                  builder.append(str.charAt(i-1));
                  count=1;
              }
              else {
                  count++;
              }
          }
         
          return builder.toString(); 
        }
    }
    

Log in to reply
 

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