Leetcode 408: Valid Word Abbreviation

问题描述:
A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as “substitution” could be abbreviated as (but not limited to):

“s10n” (“s ubstitutio n”)
“sub4u4” (“sub stit u tion”)
“12” (“substitution”)
“su3i1u2on” (“su bst i t u ti on”)
“substitution” (no substrings replaced)
Note that “s55n” (“s ubsti tutio n”) is not a valid abbreviation of “substitution” because the replaced substrings are adjacent.

Given a string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

判断是否为合法缩写

思路:
初始设结果字符串为空
abbr逐个遍历,若遇到字符,则加到结果里,调整word中指针;若遇到数字,将该位转化成数字,再查看下一位是否为数字,若是则继续更新数字,若不是则考虑结算本阶段所获得的数字。拿到结算后的数字后,判断该数字是否有效:若数字大于剩下的所有字符长度,则无效返回false;否则把word中这么长的子字符串加到结果里,调整word中的指针,清空num中本轮所获得的数字。

代码改了三遍,有些细节还是没注意:比如说数字部分出现以0开头的时候,因为abbr中所有连续的数字都必须是有效的数字,所以其最高位不能是零。即当sum的值为0且当前字符也为0时,abbr中表示的数字无效。

class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        String result = "";
        int wordPointer = 0;
        int num=0;
        for(int i=0; i<abbr.length(); i++){
            if(abbr.charAt(i)>='a'){
                result = result+abbr.charAt(i); //we can add char to string in java
                wordPointer++;
            }
            else{
                if((num==0)&&(abbr.charAt(i)=='0')) return false;
                num=num*10+(abbr.charAt(i)-'0');
                if(((i+1)<abbr.length()&&(abbr.charAt(i+1)>='a'))||(i+1==abbr.length())){
                    if(num>word.length()-wordPointer) return false;
                    else{
                        result = result+word.substring(wordPointer, wordPointer+num);
                        wordPointer=wordPointer+num;
                        num=0;
                    }
                }
            }
        }
        return result.equals(word);
    }
}

你可能感兴趣的:(leetcode)