• Valid Word Abbreviation


    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=’a‘, abbr=’01‘, test case return false。因此,所有leading zeros的temp都需要返回false。

     1 class Solution {
     2 public:
     3     bool validWordAbbreviation(string word, string abbr) {
     4         int wordIndex = 0, abbrIndex = 0;
     5         while (wordIndex < word.size()) {
     6             int abbrIndexEnd = abbrIndex;
     7             while (abbrIndexEnd < abbr.size() && isdigit(abbr[abbrIndexEnd]))
     8                 abbrIndexEnd++;
     9             
    10             // is a char and we need to check whether word[wordIndex] = abbr[abbrIndex]
    11             if (abbrIndexEnd == abbrIndex) {
    12                 if (word[wordIndex] != abbr[abbrIndex]) return false;
    13                 wordIndex++;
    14                 abbrIndex++;
    15             } else {
    16                 string temp = abbr.substr(abbrIndex, abbrIndexEnd - abbrIndex);
    17                 if (temp[0] == '0') return false;
    18                 int abbrLength = atoi(temp.c_str());
    19                 wordIndex += abbrLength;
    20                 abbrIndex = abbrIndexEnd;
    21             }
    22         }
    23         return wordIndex == word.size() && abbrIndex == abbr.size();
    24     }
    25 };
  • 相关阅读:
    获取网络时间,减轻自己服务器的请求压力
    mysql学习记录(windows)
    Docker 部署本地pip源
    npm : 无法加载文件 D:vueProject odejs ode_global pm.ps1
    微信小程序没有找到可构建的npm包
    vue 记录 mode:history 模式 踩过的坑
    Linux学习笔记
    kafka监控 Kafka-eagle-web
    vi 分屏 --(visual 可视模式)
    [安卓网络入门] 获取天气
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6076220.html
Copyright © 2020-2023  润新知