日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

408. Valid Word Abbreviation

發布時間:2023/11/30 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 408. 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.

鏈接:https://leetcode.com/problems/valid-word-abbreviation/#/description

3/22/2017

注意:

1. 第8行判斷是否有leading的0,我認為這個屬于invalid input。不過既然是google,需要仔細檢查所有可能。

2. 遇到char時,index如何加,比較之后是否加。其實,在比較之后,之前inInteger的狀態已經無所謂了,所以都需要+1

1 public class Solution { 2 public boolean validWordAbbreviation(String word, String abbr) { 3 boolean inInteger = false; 4 int number = 0; 5 int index = 0; 6 for (int i = 0; i < abbr.length(); i++) { 7 if (Character.isDigit(abbr.charAt(i))) { 8 if (!inInteger && abbr.charAt(i) - '0' == 0) return false; 9 number = number * 10 + abbr.charAt(i) - '0'; 10 inInteger = true; 11 } else { 12 if (inInteger) { 13 index += number; 14 inInteger = false; 15 number = 0; 16 } 17 if (index >= word.length()) return false; 18 if (word.charAt(index) != abbr.charAt(i)) return false; 19 index += 1; 20 } 21 } 22 if (inInteger) { 23 index += number; 24 } 25 if (index != word.length()) return false; 26 return true; 27 } 28 }

別人的思路:

1. 每次先比較2者是否相同,若不同查abbr是否是<=0或者>9(注意這里就排除了leading 0),再記錄abbr index遍歷abbr直到abbr的值不為數字,同時word加上中間的間隔。下次比較可以有結論。

2. 有個外國老哥,總是有很巧妙的方法:

1 public boolean validWordAbbreviation(String word, String abbr) { 2 return word.matches(abbr.replaceAll("[1-9]\\d*", ".{$0}")); 3 }

其他討論:https://discuss.leetcode.com/category/535/valid-word-abbreviation

轉載于:https://www.cnblogs.com/panini/p/6609229.html

總結

以上是生活随笔為你收集整理的408. Valid Word Abbreviation的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。