LeetCode 408. 有效单词缩写

    技术2023-10-16  75

    文章目录

    1. 题目2. 解题

    1. 题目

    给一个 非空 字符串 s 和一个单词缩写 abbr ,判断这个缩写是否可以是给定单词的缩写。

    字符串 “word” 的所有有效缩写为:

    ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 注意单词 "word" 的所有有效缩写仅包含以上这些。 任何其他的字符串都不是 "word" 的有效缩写。 注意: 假设字符串 s 仅包含小写字母且 abbr 只包含小写字母和数字。 示例 1: 给定 s = "internationalization", abbr = "i12iz4n": 函数返回 true. 示例 2: 给定 s = "apple", abbr = "a2e": 函数返回 false.

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-word-abbreviation 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    2. 解题

    易错例子 "a" "01" 预期: false "internationalization" "i5a11o1" 预期: true 等效长度一致数字不能有前导零 class Solution { public: bool validWordAbbreviation(string word, string abbr) { int i = 0, n = 0, j = 0; while(i<word.size() && j < abbr.size()) { n = 0; if(isdigit(abbr[j])) { if(abbr[j]=='0')//"a","01" return false; while(j < abbr.size() && isdigit(abbr[j])) n = n*10+abbr[j++]-'0'; } i += n; if(i<word.size() && j<abbr.size() && word[i] != abbr[j]) return false; else if((i<word.size()&&j>=abbr.size())||(i>=word.size()&&j<abbr.size())) return false; else if(i==word.size() && j==abbr.size()) return true;//这里加一条,可能以数字结尾,下面++,出了循环,最后条件不成立 i++,j++; } return i==word.size() && j==abbr.size(); } };

    4 ms 6 MB


    长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!

    Processed: 0.010, SQL: 9