Apex Coding Interview Challenge #5

Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

s = "3[a]2[bc]", return "aaabcbc"
s = "3[a2[c]]", return "accaccacc"
s = "2[abc]3[cd]ef", return "abcabccdcdcdef"

DecodeHelper class

public class DecodeHelper {

    private Integer idx; 
    private String zero;

    public String decodeString(String s) {
        zero ='0';
        idx = 0;
        return decodeStringHelper(s);
    }
    
    private String decodeStringHelper(String s) {
     String ans = '';
     Integer repeat = 0;

     while (idx < s.length()) {
         Integer ch = s.charAt(idx);
         Integer[] intArr = new Integer[1];
         intArr[0] = ch;
         String chStr = String.fromCharArray(intArr);
         if (chStr == ']') {
             return ans;
         } else if (chStr == '[') {
             ++idx;
             String str = decodeStringHelper(s);
             while (repeat > 0) {
                 ans+=str;
                 --repeat;
             }
         } else if (chStr.isNumeric()) {
             repeat = repeat * 10 + ch - zero.charAt(0);
             
         } else {
             ans+=chStr;
         }
         ++idx;
     }
     return ans;
   }
}

DecodeHelper Test

@isTest class DecodeHelperTest {

    @isTest static void testDecodeString(){
        Test.startTest();
            DecodeHelper dh = new DecodeHelper();
            String decodedString1 = dh.decodeString('3[a]2[bc]');
            System.assertEquals(decodedString1, 'aaabcbc');
            String decodedString2 = dh.decodeString('3[a2[c]]');
            System.assertEquals(decodedString2, 'accaccacc');
            String decodedString3 = dh.decodeString('2[abc]3[cd]ef');
            System.assertEquals(decodedString3, 'abcabccdcdcdef');
        Test.stopTest();
    }
}

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s