Grokking 75: Top Coding Interview Questions
0% completed
Solution: Comparing Strings containing Backspaces
Problem Statement
Given two strings containing backspaces (identified by the character ‘#’), check if the two strings are equal.
Example 1:
Input: str1="xy#z", str2="xzz#"
Output: true
Explanation: After applying backspaces the strings become "xz" and "xz" respectively.
Example 2:
Input: str1="xy#z", str2="xyz#"
Output: false
Explanation: After applying backspaces the strings become "xz" and "xy" respectively.
Example 3:
Input: str1="xp#", str2="xyz##"
Output: true
Explanation: After applying backspaces the strings become "x" and "x" respectively.
.....
.....
.....
Like the course? Get enrolled and start learning!
Denys Stopkin
· a year ago
static std::string deleteBackspaces(const std::string& str)
{
std::string result;
for (int i = 0; i < str.size(); ++i)
{
if (str[i] != '#')
{
result.push_back(str[i]);
}
else
{
if (!result.empty())
{
result.pop_back();
}
}
}
return result;
}
static bool compare(const std::string& str1, const std::string& str2)
{
return deleteBackspaces(str1) == deleteBackspaces(str2);
}