?LeetCode刷題實(shí)戰(zhàn)408:有效單詞縮寫
Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.
示例
示例 1:
給定 s = "internationalization", abbr = "i12iz4n":
函數(shù)返回 true.
?
示例 2:
給定 s = "apple", abbr = "a2e":
函數(shù)返回 false.
解題
https://blog.csdn.net/qq_29051413/article/details/108846427
class?Solution?{
????public?boolean?validWordAbbreviation(String word, String abbr)?{
????????char[] chars = abbr.toCharArray();
????????int?num = 0; // 縮寫中的數(shù)字,不能出現(xiàn)前導(dǎo)0
????????int?next = 0; // 遍歷 chars 的指針
????????for?(char?c : chars) {
????????????// 如果是數(shù)字,則拼接成最后的樣子
????????????if?(c >= '0'?&& c <= '9') {
????????????????// 前導(dǎo)0數(shù)字不合法
????????????????if?(num == 0?&& c == '0') return?false;
????????????????num = num * 10?+ (c - '0');
????????????????continue;
????????????}
????????????next = next + num; // 更新指針
????????????// 如果 next 超出了 word 的長度,說明不是 word 的縮寫
????????????// 或者,如果 word 和 abbr 在 next 位置的字符不一致,則說明不是 word 的縮寫
????????????if?(next >= word.length() || (word.charAt(next) != c)) {
????????????????return?false;
????????????}
????????????next++;
????????????num = 0;
????????}
????????return?next + num == word.length();
????}
}
LeetCode1-400題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)401:二進(jìn)制手表
LeetCode刷題實(shí)戰(zhàn)402:移掉 K 位數(shù)字
LeetCode刷題實(shí)戰(zhàn)403:青蛙過河
LeetCode刷題實(shí)戰(zhàn)404:左葉子之和
LeetCode刷題實(shí)戰(zhàn)405:數(shù)字轉(zhuǎn)換為十六進(jìn)制數(shù)
LeetCode刷題實(shí)戰(zhàn)406:根據(jù)身高重建隊列
LeetCode刷題實(shí)戰(zhàn)407:接雨水 II
評論
圖片
表情
