Pattern similar to compress string


  • 0
    R

    String sayPrev(String prev) here is similar to Compress string with little modifications of

    1. Do not check if the end result is actually result in smaller string
    2. Count preceding the character
      i.e. in Compress string problem for given input: sssscccdd, expected output: s4c3d2
    class Solution {
        public String countAndSay(int n) {
            if(n<1) {
                return null;
            } else if(n==1) {
                return "1";
            } else {
                String prev = countAndSay(n-1);        
                return sayPrev(prev);
            }
        }
        
        private String sayPrev(String prev) {
            StringBuilder cur = new StringBuilder();
                int count=1;
                char c1 = prev.charAt(0);
                for(int i=1; i<prev.length(); i++) {
                    char c2 = prev.charAt(i);
                    if(c1==c2) {
                        count++;
                    } else {
                        cur.append(count);
                        cur.append(c1);
                        count = 1;
                        c1 = c2;
                    }
                }
                cur.append(count);
                cur.append(c1);
                return cur.toString();
        }
    }
    

Log in to reply
 

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