首页 > 代码库 > Valid Word Abbreviation Leetcode
Valid Word Abbreviation Leetcode
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.
反正每次自己七改八改然后看top solution就会觉得自己逻辑混乱。。。= =
以下是我写的代码,有点难懂。。。
public class Solution { public boolean validWordAbbreviation(String word, String abbr) { int index1 = 0; int index2 = 0; char[] a = word.toCharArray(); char[] b = abbr.toCharArray(); while (index1 < a.length && index2 < b.length) { if (a[index1] != b[index2]) { int num = 0; if (index2 < b.length && b[index2] - ‘0‘ <= 0 || b[index2] - ‘0‘ > 9) { return false; } while (index2 < b.length && b[index2] - ‘0‘ >= 0 && b[index2] - ‘0‘ <= 9) { num = num * 10 + b[index2] - ‘0‘; index2++; } if (num == 0) { return false; } else { int count = 0; while (count < num) { if (count < num && index1 > a.length - 1) { return false; } index1++; count++; } } } else { index1++; index2++; } } return index1 == a.length && index2 == b.length; } }
看了下top solution重新写的
public class Solution { public boolean validWordAbbreviation(String word, String abbr) { int index1 = 0; int index2 = 0; char[] a = word.toCharArray(); char[] b = abbr.toCharArray(); while (index1 < a.length && index2 < b.length) { if (a[index1] == b[index2]) { index1++; index2++; continue; } if (b[index2] - ‘0‘ <= 0 || b[index2] - ‘0‘ > 9) { System.out.println(1); return false; } int num = 0; while (index2 < b.length && b[index2] - ‘0‘ >= 0 && b[index2] - ‘0‘ <= 9) { num = num * 10 + b[index2] - ‘0‘; index2++; } index1 = index1 + num; if (index1 < a.length && index2 < b.length && a[index1] != b[index2]) { return false; } } return index1 == a.length && index2 == b.length; } }
其中
if (index1 < a.length && index2 < b.length && a[index1] != b[index2]) { return false; }
这里可以省略的。
整体思路就是如果一样,就continue,不一样就看第一个数字是不是0,是0就false。然后把数字取出来,给index1加上,看看最后两个是不是都恰好把数组遍历了一遍。
反正这道题到时候需要回顾的。。。不是这里错就是那里错。
Valid Word Abbreviation Leetcode
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。