[Algo] 292. String Abbreviation Matching

Word “book” can be abbreviated to 4, b3, b2k, etc. Given a string and an abbreviation, return if the string matches the abbreviation.

Assumptions:

  • The original string only contains alphabetic characters.
  • Both input and pattern are not null.
  • Pattern would not contain invalid information like "a0a","0".

Examples:

  • pattern “s11d” matches input “sophisticated” since “11” matches eleven chars “ophisticate”.
public class Solution {
  public boolean match(String input, String pattern) {
    // Write your solution here
    int iIndex = 0;
    int pIndex = 0;
    char[] charArr = pattern.toCharArray();
    while (iIndex < input.length() && pIndex < pattern.length()) {
      char cur = charArr[pIndex];
      if (Character.isLetter(cur)) {
        if (cur != input.charAt(iIndex)) {
          return false;
        }
        iIndex += 1;
        pIndex += 1;
      } else if (Character.isDigit(cur)) {
        int num = 0;
        while (pIndex < charArr.length && Character.isDigit(charArr[pIndex])) {
          num = 10 * num + (int)(charArr[pIndex] - '0');
          pIndex += 1;
        }
        iIndex += num;
      }
    }
    return iIndex == input.length() && pIndex == pattern.length();
  }
}

 

posted @ 2020-02-20 11:09  xuan_abc  阅读(255)  评论(0编辑  收藏  举报