LeetCode 408: Valid Word Abbreviation Solution
Master LeetCode problem 408 (Valid Word Abbreviation), a easy 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.
408. Valid Word Abbreviation
Problem Explanation
Explanation:
Given a non-empty string s and an abbreviation abbr, return whether the string matches the abbreviation.
To solve this problem, we can iterate through both the input string and the abbreviation simultaneously. We compare characters at each position:
- If the characters match, we move both pointers forward.
- If the character in the abbreviation is a digit, we need to skip that many characters in the input string.
- If any mismatch is found or we reach the end of either string or abbreviation prematurely, we return false.
Finally, if we successfully iterate through both strings, we return true.
- Time complexity: O(n), where n is the length of the input string.
- Space complexity: O(1)
:
Solution Code
class Solution {
public boolean validWordAbbreviation(String word, String abbr) {
int i = 0, j = 0;
while (i < word.length() && j < abbr.length()) {
if (word.charAt(i) == abbr.charAt(j)) {
i++;
j++;
} else if (abbr.charAt(j) >= '1' && abbr.charAt(j) <= '9') {
int num = 0;
while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) {
num = num * 10 + abbr.charAt(j) - '0';
j++;
}
i += num;
} else {
return false;
}
}
return i == word.length() && j == abbr.length();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 408 (Valid Word Abbreviation)?
This page provides optimized solutions for LeetCode problem 408 (Valid Word Abbreviation) 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 408 (Valid Word Abbreviation)?
The time complexity for LeetCode 408 (Valid Word Abbreviation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 408 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 408 in Java, C++, or Python.