Leetcode: Valid Word Abbreviation

Posted neverlandly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode: Valid Word Abbreviation相关的知识,希望对你有一定的参考价值。

Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

A string such as "word" contains only the following valid abbreviations:

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word".

Note:
Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

Example 1:
Given s = "internationalization", abbr = "i12iz4n":

Return true.
Example 2:
Given s = "apple", abbr = "a2e":

Return false.

 

 1 public class Solution {
 2     public boolean validWordAbbreviation(String word, String abbr) {
 3         int i = 0, j = 0;
 4         while (i<word.length() && j<abbr.length()) {
 5             if (!isDigit(abbr.charAt(j))) {
 6                 if (word.charAt(i) != abbr.charAt(j)) return false;
 7                 i++;
 8                 j++;
 9             }
10             else {
11                 int num = 0;
12                 while (j<abbr.length() && isDigit(abbr.charAt(j))) {
13                     num = num*10 + (int)(abbr.charAt(j)-‘0‘);
14                     if (num == 0) return false; //"001" with ‘0‘ at front should return false
15                     j++;
16                 }
17                 i = i + num;
18             }
19         }
20         if (i==word.length() && j==abbr.length()) return true;
21         return false;
22     }
23     
24     public boolean isDigit(char c) {
25         if (c>=‘0‘ && c<=‘9‘) return true;
26         return false;
27     }
28 }

 

以上是关于Leetcode: Valid Word Abbreviation的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 409: Valid Word Abbreviation

[LeetCode] Valid Word Abbreviation 验证单词缩写

408. Valid Word Abbreviation --字符串处理

408. Valid Word Abbreviation

408. Valid Word Abbreviation

LeetCode Valid Word Square