Check if an Original String Exists Given Two Encoded Strings - Problem
An original string, consisting of lowercase English letters, can be encoded by the following steps:
- Arbitrarily split it into a sequence of some number of non-empty substrings.
- Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
- Concatenate the sequence as the encoded string.
For example, one way to encode an original string "abcdefghijklmnop" might be:
- Split it as a sequence:
["ab", "cdefghijklmn", "o", "p"]. - Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes
["ab", "12", "1", "p"]. - Concatenate the elements of the sequence to get the encoded string:
"ab121p".
Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.
Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.
Input & Output
Example 1 — Different Interpretations
$
Input:
s1 = "a5b", s2 = "a5b"
›
Output:
true
💡 Note:
Both strings are identical, so they can definitely encode the same original string (either "a5b" or "a" + 5 characters + "b")
Example 2 — Number as Length
$
Input:
s1 = "ab", s2 = "a2"
›
Output:
false
💡 Note:
s1 = "ab" means original has 'a' then 'b'. s2 = "a2" could mean 'a' + 2 characters, but that would be 3 total chars vs 2 in s1
Example 3 — Complex Case
$
Input:
s1 = "a5b", s2 = "abc"
›
Output:
false
💡 Note:
s1 could be "a5b" (3 chars) or "a" + 5chars + "b" (7 chars). s2 is "abc" (3 chars). Only 3-char interpretation works, but "a5b" ≠ "abc"
Constraints
- 1 ≤ s1.length, s2.length ≤ 40
- s1 and s2 consist of digits 1-9 and lowercase English letters
- The number of consecutive digits in s1 and s2 does not exceed 3
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two encoded strings with letters and digits
2
Process
Try different interpretations of digits
3
Output
True if both can encode same original
Key Takeaway
🎯 Key Insight: Track character count difference to determine if both strings can represent the same original
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code