美文网首页
408-有效单词缩写

408-有效单词缩写

作者: 饮酒醉回忆 | 来源:发表于2019-07-27 20:19 被阅读0次

    有效单词缩写

    题目

    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.

    总体来说题目的意思就是给定一个字符串,以下的形式是合法的缩写:

    ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

    要注意仅有这些是合法的,其他都是非法的.

    注意:所有的缩写和给定的字符都是小写的.

    例1:

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

    例2

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

    思路

    我们观察到也就是字符还是字符的位置,中间的数字就是代表了经过的位数.

    可以分成两个指针.一个指针指向word,一个指针指向abbr.如果是相同字符,则同时移动.如果abbr是数字,则将abbr的指针移动.然后使用截取得到数字,将word的指针直接移动.如果是不相同字符,则直接返回.最后只需要比较长度与原长度是否相等即可.

    代码

    
    class Solution {
       public boolean validWordAbbreviation(String word, String abbr) {
                int wordIndex = 0;
                int abbrIndex = 0;
                int wordLength = word.length();
                int abbrLength = abbr.length();
                //如果abbr的长度已经比word要长,则肯定为false
                if(abbrLength > wordLength){
                        return false;
                }
                while (abbrIndex < abbrLength && wordIndex < wordLength) {
                    if (word.charAt(wordIndex) == abbr.charAt(abbrIndex)) {
                        wordIndex++;
                        abbrIndex++;
                    } else if (Character.isDigit(abbr.charAt(abbrIndex))) {
                        int start = abbrIndex;
                        while (abbrIndex < abbr.length() && Character.isDigit(abbr.charAt(abbrIndex))) {
                            abbrIndex++;
                        }
                        int count = Integer.valueOf(abbr.substring(start, abbrIndex));
                        wordIndex += count;
                    } else {
                        return false;
                    }
                }
                return wordIndex == wordLength && abbrIndex == abbrLength;
            }
    

    相关文章

      网友评论

          本文标题:408-有效单词缩写

          本文链接:https://www.haomeiwen.com/subject/vofyrctx.html