资讯专栏INFORMATION COLUMN

[LeetCode] 408. Valid Word Abbreviation

zone / 966人阅读

Problem

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.

Solution
class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        if (word == null || abbr == null) return false;
        int i = 0, j = 0;
        while (i < word.length() && j < abbr.length()) {
            char ch1 = word.charAt(i), ch2 = abbr.charAt(j);
            if (ch1 == ch2) {
                i++;
                j++;
            } else if (ch2 >= "1" && ch2 <= "9") {
                int start = j;
                while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) j++;
                int count = Integer.valueOf(abbr.substring(start, j));
                i += count;
            } else return false;
        }
        return i == word.length() && j == abbr.length();
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72242.html

相关文章

  • 408. Valid Word Abbreviation

    Given s = internationalization, abbr = i12iz4n: Return true. Given s = apple, abbr = a2e: Return false. public class Solution { public boolean validWordAbbreviation(String word, String abbr) { ...

    DangoSky 评论0 收藏0
  • Word Abbreviation

    摘要:链接注意第一个数字是的情况,这种也是不合法的。还有一个注意的就是要想和有相同的缩写,长度必须和它相同,所以只保留长度相同的。注意剪枝,当前长度已经超过就不需要继续了。二进制的做法是这样的,先对字典里面的单词进行处理。 Valid Word Abbreviation 链接:https://leetcode.com/problems... 注意第一个数字是0的情况,[a, 01]这种也是不...

    Y3G 评论0 收藏0
  • [LeetCode]Generalized Abbreviation

    摘要:分析这道题第一步一定要理解题意,首先要考虑的是会有多少种结果。仔细观察会发现,最终会有种结果。然后就很显然应该用每次存下当前结果,然后继续。 Generalized Abbreviation Write a function to generate the generalized abbreviations of a word. Example:Given word = word, ...

    ZoomQuiet 评论0 收藏0
  • 320. Generalized Abbreviation

    摘要:题目链接要输出所有的结果,标准思路。也可以做,保留为,改为数字的为,然后结果就是这么多,每个数学遍历一遍求对应的即可。 320. Generalized Abbreviation 题目链接:https://leetcode.com/problems... 要输出所有的结果,backtracking标准思路。 public class Solution { public List...

    yangrd 评论0 收藏0
  • Unique Word Abbreviation LC解题记录

    摘要:题目内容这题也是锁住的,通过率只有左右。另外,字典里面只有两个的时候,也是返回。最后再说两句距离上一篇文章过了一段时间了,这段时间搬家再适应新环境,解决心理问题。 题目内容 An abbreviation of a word follows the form . Below are some examples of word abbreviations: a) it ...

    curried 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<