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.
Solutionclass 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(); } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72242.html
Given s = internationalization, abbr = i12iz4n: Return true. Given s = apple, abbr = a2e: Return false. public class Solution { public boolean validWordAbbreviation(String word, String abbr) { ...
摘要:鏈接注意第一個數字是的情況,這種也是不合法的。還有一個注意的就是要想和有相同的縮寫,長度必須和它相同,所以只保留長度相同的。注意剪枝,當前長度已經超過就不需要繼續了。二進制的做法是這樣的,先對字典里面的單詞進行處理。 Valid Word Abbreviation 鏈接:https://leetcode.com/problems... 注意第一個數字是0的情況,[a, 01]這種也是不...
摘要:分析這道題第一步一定要理解題意,首先要考慮的是會有多少種結果。仔細觀察會發現,最終會有種結果。然后就很顯然應該用每次存下當前結果,然后繼續。 Generalized Abbreviation Write a function to generate the generalized abbreviations of a word. Example:Given word = word, ...
摘要:題目鏈接要輸出所有的結果,標準思路。也可以做,保留為,改為數字的為,然后結果就是這么多,每個數學遍歷一遍求對應的即可。 320. Generalized Abbreviation 題目鏈接:https://leetcode.com/problems... 要輸出所有的結果,backtracking標準思路。 public class Solution { public List...
摘要:題目內容這題也是鎖住的,通過率只有左右。另外,字典里面只有兩個的時候,也是返回。最后再說兩句距離上一篇文章過了一段時間了,這段時間搬家再適應新環境,解決心理問題。 題目內容 An abbreviation of a word follows the form . Below are some examples of word abbreviations: a) it ...
閱讀 3420·2021-11-15 11:39
閱讀 1552·2021-09-22 10:02
閱讀 1309·2021-08-27 16:24
閱讀 3596·2019-08-30 15:52
閱讀 3412·2019-08-29 16:20
閱讀 824·2019-08-28 18:12
閱讀 550·2019-08-26 18:27
閱讀 716·2019-08-26 13:32