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.
两根同向指针。
一根指着abbr一根指着word,ptrA发现数字的时候要停下来,取数字,帮ptrW也跳这么远,然后接着比。最后确认一下两根指针是不是都跑到各自的最后了即可。
细节:
1.API。isLetter(()方法的正确写法是Character.isLetter(abbr.charAt(pa))而不是abbr.charAt(pa).isLetter(),char没有方法,只有Character有static方法
2.abbr里的0只有101这种数字里才算有效,以0开头不行,比如"a" "01"这种case应输出false,因为题意里说的word只有w1rd这几种形式,而没有w01rd的形式,可以说算是给的比较明确了。具体当然和面试官沟通。
我的实现:
class Solution { public boolean validWordAbbreviation(String word, String abbr) { int pw = 0; int pa = 0; while (pw < word.length() && pa < abbr.length()) { // 注意API!不是abbr.charAt(pa).isLetter(),char没有方法,只有Character有static方法 if (Character.isLetter(abbr.charAt(pa))) { if (pw >= word.length() || word.charAt(pw) != abbr.charAt(pa)) { return false; } pw++; pa++; } else if (abbr.charAt(pa) == ‘0‘) { // 注意0不能算,"a" "01"这种case应输出false,具体当然和面试官沟通。 return false; } else { int number = 0; while (pa < abbr.length() && Character.isDigit(abbr.charAt(pa))) { number = number * 10 + abbr.charAt(pa) - ‘0‘; pa++; } pw += number; } } return pw == word.length() && pa == abbr.length(); } }
九章实现
public 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) > ‘0‘) && (abbr.charAt(j) <= ‘9‘)) { //notice that 0 cannot be included int start = j; while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) { j++; } i += Integer.valueOf(abbr.substring(start, j)); } else { return false; } } return (i == word.length()) && (j == abbr.length()); } }
原文地址:https://www.cnblogs.com/jasminemzy/p/9612341.html