Valid Word Abbreviation
来源:互联网 发布:安卓软件培训 编辑:程序博客网 时间:2024/05/19 12:41
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 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(); }
0 0
- 408. Valid Word Abbreviation
- Valid Word Abbreviation
- 408. Valid Word Abbreviation
- 【Leetcode】408. Valid Word Abbreviation
- LeetCode 408. Valid Word Abbreviation
- LeetCode 408. Valid Word Abbreviation
- [leetcode] 408. Valid Word Abbreviation 解题报告
- [Leetcode] 408. Valid Word Abbreviation 解题报告
- word abbreviation
- 【vim】word abbreviation
- *LeetCode-Unique Word Abbreviation
- [LeetCode288]Unique Word Abbreviation
- Unique Word Abbreviation
- Leetcode Unique Word Abbreviation
- Unique Word Abbreviation
- 288. Unique Word Abbreviation
- 288. Unique Word Abbreviation
- leetcode 288: Unique Word Abbreviation
- Windows下程序入口函数与_security_init_cookie
- Dockerfile 中文参考文档
- 基于CheckStackVars的安全检查
- jstl标签库使用
- Leetcode Guess Number Higher or Lower
- Valid Word Abbreviation
- 数据分析站点导航
- 基于 HTML5 的 Web SCADA 报表
- 《一天攻破K60》笔记(使用山外库5.3版本)
- 正则表达式(括号)、[中括号]、{大括号}的区别小结
- spring配置c3p0报错Could not load driverClass oracle.jdbc.OracleDriver
- 五种Sublime text 3同时快速编辑多行内容
- 我的第一个博客
- 常用正则表达式(手机,电话,身份证)