Created
February 14, 2024 13:18
-
-
Save ritik-agrawal/0ef5ff33d35d7f57464636e44cc72c56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String decodeString(String s) { | |
var retVal = new StringBuilder(); | |
var len = s.length(); | |
var i = 0; | |
while(i < len){ | |
var chr = s.charAt(i); | |
if (Character.isDigit(chr)){ | |
i = valueOf((i) , s, retVal); | |
} else { | |
retVal.append(chr); | |
i++; | |
} | |
} | |
return retVal.toString(); | |
} | |
private Integer valueOf(int i, String s, StringBuilder result){ | |
var repStr = getFullRep(i, s); | |
var repLen = repStr.length(); | |
var rep = Integer.valueOf(repStr); | |
var of = new StringBuilder(); | |
var len = s.length(); | |
var j = ((i+ repLen -1)+2); | |
while (j < len){ | |
var chr = s.charAt(j); | |
if (Character.isDigit(chr)){ | |
j = valueOf(j, s, of); | |
} else if (Objects.equals(chr, ']')){ | |
result.append(compute(rep, of.toString())); | |
return (j+1); | |
} else { | |
of.append(chr); | |
j++; | |
} | |
} | |
return (j+1); | |
} | |
private String compute(int rep, String of){ | |
var retVal = new StringBuilder(); | |
for (int i = 0; i < rep; i++){ | |
retVal.append(of); | |
} | |
return retVal.toString(); | |
} | |
private String getFullRep(int i, String s){ | |
var len = s.length(); | |
var retVal = new StringBuilder(); | |
while( | |
i < len && | |
Character.isDigit(s.charAt(i)) | |
){ | |
retVal.append(s.charAt(i++)); | |
} | |
return retVal.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Leetcode Question
Link: https://leetcode.com/problems/decode-string/?envType=study-plan-v2&envId=leetcode-75
Achievement
I write the above code and it beats 100% of the total submissions in terms of runtime with the value of 0 ms.