The helper method and the char count do not work as I wanted
I wanted to solve this leetcode puzzle with recursion https://leetcode.com/problems/decode-string/
This is my WIP, the count variable (to count chars in the bracket) and the recursion line do not seem to work. For example, this code prints out
aabc
while it was supposed to be print out like aaabcbc
(for the case 3[a]2[bc]). Could anyone kindly point me in the right direction?
``LeetCode
Decode String - LeetCode
Can you solve this real interview question? Decode String - 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.
You may assume that the input string is always valid;...
2 Replies
one immediate problem is that you're setting count to 0 every iteration of your loop through the characters
so when you call Solver, count will always be 1
ok, I took the initialisation of
count
to outside the first loop like this
public string DecodeString(string s) {
var sb = new StringBuilder();
int count = 0;
for(int i = 0; i < s.Length; i++){
if(Char.IsDigit(s[i])){
count = 10*count + (s[i]-'0');
} else if (s[i] == '[')
{
count++;
string teilStr = Solver(count, s, sb);
string decodedString = DecodeString(teilStr);
sb.Append(decodedString);
count = 0;
} else if (Char.IsLetter(s[i])){
count++;
sb.Append(s[i]);
}
}
return sb.ToString();
}
private string Solver(int count, string s, StringBuilder sb)
{
string stringToAppend = "";
int openBracket = 0;
for(int i = 1; i < count; i++){
openBracket++;
sb.Append(s[i]);
}
openBracket--;
return sb.ToString();
}
}
But this code now gives me the IndexOutOfRangeException 😅