首页 > 代码库 > Leetcode: Valid Word Abbreviation

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