Valid Word Abbreviation

225 篇文章 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.

Show Company Tags
Show Tags
Show Similar Problems

这道题思路比较简单,但是后来处理边界条件上花了时间比较久。

思路是使用两个指针,分别从word, abbr的头开始走起,index2碰到数字的话,首先判断开头是否为0(这一点我挺费解的,为啥不能为0,后来测试用例告诉我这样不可以)。然后让index1 走相应的距离,然后再判断对应index1 index2的位置的值是否一样。不一样的话return false.

代码:

public boolean validWordAbbreviation(String word, String abbr) {
        if(word == null || word.length() == 0 || abbr == null || abbr.length() == 0) return false;

        int index1 = 0;
        int index2 = 0;
        int offset = 0;
        while(index1<word.length() && index2 < abbr.length()){


            char char2 = abbr.charAt(index2);
            if(char2>='0' && char2 <='9'){
                if(char2 == '0') return false;
                while(char2>='0' && char2 <='9'){
                    offset = offset * 10 + char2 - '0';
                    index2++;
                    if(index2 == abbr.length()) break;
                    char2 = abbr.charAt(index2);
                }
            }
            //System.out.println("offset"+ offset);
            index1 += offset;
            offset = 0;
            if(index1 >= word.length()) break;
            char char1 = word.charAt(index1);
            if(char1 != char2){
                return false;
            }
            index1++;
            index2++;
        }
        return index1 == word.length() && index2 == abbr.length();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值