• [LintCode] Check Word Abbreviation


    Given a non-empty string word 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

    Notice that only the above abbreviations are valid abbreviations of the string word. Any other string is not a valid abbreviation of word.

    Example

    Example 1:

    Given s = "internationalization", abbr = "i12iz4n":
    Return true.
    

    Example 2:

    Given s = "apple", abbr = "a2e":
    Return false.


    Solution.
    This problem is fairly simple and straightforward. The only tricky part is all the corner cases.


    1. if there is a number in the abbr string, parse it to num.
    2. advance the index of word by num.
    3. if both i and j are still in bound, check if match or not.
    4. repeat the above steps until either i or j is out of bound.
    5. check if both i and j are out of bound.

     1 public class Solution {
     2     public boolean validWordAbbreviation(String word, String abbr) {
     3         if(abbr == null || abbr.length() == 0){
     4             return false;
     5         }
     6         int i = 0;
     7         int j = 0;
     8         int num = 0;
     9         while(i < word.length() && j < abbr.length()){
    10             while(j < abbr.length() && abbr.charAt(j) >= '0' 
    11                     && abbr.charAt(j) <= '9'){
    12                 num = num * 10 + (abbr.charAt(j) - '0');   
    13                 if(num == 0){
    14                     return false;
    15                 }
    16                 j++;
    17             }
    18             i += num;
    19             num = 0;
    20             if(i >= word.length() || j >= abbr.length()){
    21                 break;
    22             }
    23             else if(word.charAt(i) != abbr.charAt(j)){
    24                 return false;    
    25             }
    26             else{
    27                 i++;
    28                 j++;
    29             }
    30         }
    31         return i == word.length() && j == abbr.length();
    32     }
    33 }

    Related Problems

    Word Abbreviation

  • 相关阅读:
    选项卡自动切换(定时器demo)
    JS基础——选项卡套选项卡(函数传参)
    JS基础——修改文本框的值(函数传参)
    JS基础——选项卡列表显示隐藏缩略图(函数传参)
    js基础——图片切换实例(函数传参)
    JS 获取元素的属性值,非内联样式
    css position 定位
    ie6-7 overflow:hidden失效问题的解决方法
    Vue自带的过滤器
    Vue数据绑定
  • 原文地址:https://www.cnblogs.com/lz87/p/6949000.html
Copyright © 2020-2023  润新知