Valid Word Abbreviation Leetcode
Posted 璨璨要好好学习
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
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的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode: Valid Word Abbreviation
Valid Word Abbreviation Leetcode
LeetCode 409: Valid Word Abbreviation