Corrupted String Recovery — Problem Statement & Solution Guide
Problem Description
Given a corrupted string with '#' and '*' characters, write a function to recover the original string by removing all '#' and '*' characters. The function should handle null or undefined input.
Examples
Input
He#lo
Output
He
Explanation: Step-by-step: Given the input string 'He#lo', we first remove all '#' characters, resulting in 'Heo'. Then, we remove all '*' characters, but since there are none, the final output is 'He'.
Input
H##*ello
Output
Helo
Explanation: Step-by-step: Given the input string 'H##*ello', we first remove all '#' characters, resulting in 'He*ello'. Then, we remove all '*' characters, resulting in 'Helo'.
Constraints
- The corrupted snapshot is a non-empty string of lowercase English letters and digits.
- The original string is a valid English word.
- The length of the corrupted snapshot does not exceed 30 characters.
- The dictionary of valid words is provided as a set of words.
Optimal Approach & Strategy
Optimal approach involves using a set of valid words and scanning the corrupted string for word boundaries, resulting in a linear time complexity of O(n) with O(26) space complexity.
Brute Force Approach
Naive approach would involve checking every substring of the corrupted string against the dictionary of valid words, resulting in an O(n^2) time complexity.
Verified Code Solutions
function recoverString(s) { if (!s) return ''; let result = ''; for (let i = 0; i < s.length; i++) { if (s[i] === '#' && i > 0 && s[i - 1] === '*') { i--; continue; } if (s[i] !== '#' && s[i] !== '*') result += s[i]; } return result; }class Solution {
public String recoverString(String s) {
if (s == null) {
return "";
}
StringBuilder stack = new StringBuilder();
for (char c : s.toCharArray()) {
if (c != '#' && c != '*') {
stack.append(c);
} else if (stack.length() > 0 && stack.charAt(stack.length() - 1) == '*') {
stack.deleteCharAt(stack.length() - 1);
}
}
return stack.toString();
}
}def recover_string(s: str) -> str:
if s is None:
return ''
stack = []
for char in s:
if char not in ['#', '*']:
stack.append(char)
elif stack and stack[-1] == '*':
stack.pop()
return ''.join(stack)function recoverString(s) { if (!s) return ''; let result = ''; for (let i = 0; i < s.length; i++) { if (s[i] === '#' && i > 0 && s[i - 1] === '*') { i--; continue; } if (s[i] !== '#' && s[i] !== '*') result += s[i]; } return result; }Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.