LeetCode 2060: Check if an Original String Exists Given Two Encoded Strings Solution
Master LeetCode problem 2060 (Check if an Original String Exists Given Two Encoded Strings), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2060. Check if an Original String Exists Given Two Encoded Strings
Problem Explanation
Explanation:
To solve this problem, we need to determine if there exists an original string that could be encoded as both s1 and s2. We can approach this problem by iterating through all possible splits of the original string and checking if each split can be encoded to match both s1 and s2.
- We start by iterating through all possible splits of the original string.
- For each split, we try to encode it to match
s1ands2. - If we find a split that matches both
s1ands2, we return true. Otherwise, we return false.
Time Complexity: The time complexity of this approach is exponential as we are iterating through all possible splits of the original string.
Space Complexity: The space complexity is O(N), where N is the length of the original string.
:
Solution Code
class Solution {
public boolean isOriginalString(String s1, String s2) {
return canEncode(s1, s2, 0, 0, "");
}
public boolean canEncode(String s1, String s2, int idx1, int idx2, String original) {
if (idx1 == s1.length() && idx2 == s2.length()) {
return true;
}
if (idx1 < s1.length() && Character.isDigit(s1.charAt(idx1))) {
int len = s1.charAt(idx1) - '0';
return canEncode(s1, s2, idx1 + 1, idx2, original + new String(new char[len]).replace("\0", "a"));
}
if (idx2 < s2.length() && Character.isDigit(s2.charAt(idx2))) {
int len = s2.charAt(idx2) - '0';
return canEncode(s1, s2, idx1, idx2 + 1, original + new String(new char[len]).replace("\0", "a"));
}
if (idx1 < s1.length() && idx2 < s2.length() && s1.charAt(idx1) == s2.charAt(idx2)) {
return canEncode(s1, s2, idx1 + 1, idx2 + 1, original + s1.charAt(idx1));
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2060 (Check if an Original String Exists Given Two Encoded Strings)?
This page provides optimized solutions for LeetCode problem 2060 (Check if an Original String Exists Given Two Encoded Strings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2060 (Check if an Original String Exists Given Two Encoded Strings)?
The time complexity for LeetCode 2060 (Check if an Original String Exists Given Two Encoded Strings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2060 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2060 in Java, C++, or Python.