Readable Java, Tasks breakdown


  • 0
    J
    public class Solution {
        public String countAndSay(int n){
            String res = Integer.toString(1);
            for(int i = 0; i< n-1; i++){
                res = countAndSaySingle(res);
            }
            return res;
        }
        public String countAndSaySingle(String num) {
            String res = "";
            char pre = num.charAt(0);
            int preidx = 0;
            for(int i = 0; i < num.length(); i++){
                if(num.charAt(i) != pre){
                    res += sayPart(pre, i - preidx);
                    pre = num.charAt(i);
                    preidx = i;
                }
            }
            res += sayPart(pre, num.length()-preidx);
            return res;
        }
        
        private String sayPart(char digit, int len){
            return ""+len + digit;
        }
    }
    

Log in to reply
 

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