LeetCode 408. Valid Word Abbreviation

本文介绍了一种判断非空字符串与其缩写形式是否匹配的算法。通过双指针技术,文章详细阐述了如何处理包含字母和数字的有效缩写,并提供了具体的实现代码。此外,还特别说明了缩写中数字的有效性和限制条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路:
1. 判断是否match,简单的方法,就是two pointer,两个指针分别指向两个string,按照规则从左往右!
2. 难点是:从abbr中提取数字并组合得到对应的integer
3. 需注意的是,abbr只能是字母和数字,而且数字不能是0或0开头的数,但“10”是合法的。

bool validWordAbbreviation(string word, string abbr) {
    int m=word.size(),n=abbr.size();
    int i=0,j=0;
    while(i<m&&j<n){
        if(abbr[j]=='0')//遇到以0开头的数字或0,非法!
            return false;
        else if(abbr[j]>='1'&&abbr[j]<='9'){
            int count=0;
            while(j<n&&abbr[j]>='0'&&abbr[j]<='9'){//0允许出现在数字中间的位置
                count=count*10+abbr[j]-'0';
                j++;
            }
            i+=count;
        }else
            if(abbr[j++]!=word[i++]) return false;
    }
    return i==m&&j==n;//corner case:保证长度相等
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值