[LeetCode] 408. Valid Word Abbreviation
A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros.
For example, a string such as "substitution"
could be abbreviated as (but not limited to):
"s10n"
("s ubstitutio n"
)"sub4u4"
("sub stit u tion"
)"12"
("substitution"
)"su3i1u2on"
("su bst i t u ti on"
)"substitution"
(no substrings replaced)
The following are not valid abbreviations:
"s55n"
("s ubsti tutio n"
, the replaced substrings are adjacent)"s010n"
(has leading zeros)"s0ubstitution"
(replaces an empty substring)
Given a string word
and an abbreviation abbr
, return whether the string matches the given abbreviation.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: word = "internationalization", abbr = "i12iz4n" Output: true Explanation: The word "internationalization" can be abbreviated as "i12iz4n" ("i nternational iz atio n").
Example 2:
Input: word = "apple", abbr = "a2e" Output: false Explanation: The word "apple" cannot be abbreviated as "a2e".
Constraints:
1 <= word.length <= 20
word
consists of only lowercase English letters.1 <= abbr.length <= 10
abbr
consists of lowercase English letters and digits.- All the integers in
abbr
will fit in a 32-bit integer.
有效单词缩写。
字符串可以用 缩写 进行表示,缩写 的方法是将任意数量的 不相邻 的子字符串替换为相应子串的长度。例如,字符串 "substitution" 可以缩写为(不止这几种方法):
"s10n" ("s ubstitutio n")
"sub4u4" ("sub stit u tion")
"12" ("substitution")
"su3i1u2on" ("su bst i t u ti on")
"substitution" (没有替换子字符串)
下列是不合法的缩写:"s55n" ("s ubsti tutio n",两处缩写相邻)
"s010n" (缩写存在前导零)
"s0ubstitution" (缩写是一个空字符串)
给你一个字符串单词 word 和一个缩写 abbr ,判断这个缩写是否可以是给定单词的缩写。子字符串是字符串中连续的非空字符序列。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-word-abbreviation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道字符串的基础题,不难,注意细节。
思路是双指针,两个指针 i, j 分别指向 word 和 abbr。如果两边指向的字母相同,则分别往前走一步;如果 abbr 这一边指向了一个不是 0 开头的数字,则我们算一下这个数字 num 到底是多少,然后让 i 指针往前走 num 步。如果顺利,最后两个指针应该是同时到达 word 和 abbr 的尾部。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean validWordAbbreviation(String word, String abbr) { 3 // corner case 4 if (word == null || abbr == null) { 5 return false; 6 } 7 8 // normal case 9 int i = 0; 10 int j = 0; 11 while (i < word.length() && j < abbr.length()) { 12 if (word.charAt(i) == abbr.charAt(j)) { 13 i++; 14 j++; 15 } else if (Character.isDigit(abbr.charAt(j)) && abbr.charAt(j) != '0') { 16 int num = 0; 17 while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) { 18 num = num * 10 + abbr.charAt(j) - '0'; 19 j++; 20 } 21 i += num; 22 } else { 23 return false; 24 } 25 } 26 return i == word.length() && j == abbr.length(); 27 } 28 }