首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。