Skip to content

Instantly share code, notes, and snippets.

@ritik-agrawal
Created February 14, 2024 13:18
Show Gist options
  • Save ritik-agrawal/0ef5ff33d35d7f57464636e44cc72c56 to your computer and use it in GitHub Desktop.
Save ritik-agrawal/0ef5ff33d35d7f57464636e44cc72c56 to your computer and use it in GitHub Desktop.
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();
}
}
@ritik-agrawal
Copy link
Author

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.

  • The solution uses stack logic.
  • Whenever a number is encountered the following string is being pushed to the stack with two values i.e rep- repetitions and of that stores the strings whose repetitions are required

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment