Java straightforward, easy understand solution.


  • 4
    N
    public boolean validWordAbbreviation(String word, String abbr) {
            if(word == null || abbr == null) return false;
            int num = 0;
            int idx = 0;
            
            for(char c: abbr.toCharArray()){
                if(c == '0' && num == 0) return false;
                if(c >= '0' && c <= '9'){
                    num = num*10 + (c-'0');
                }else{
                    idx += num;
                    if(idx >= word.length() || c != word.charAt(idx)) return false;
                    num = 0;
                    idx++;
                }
            }
            
            return idx+num == word.length() ? true : false;
        }
    
    

  • 1
    G

    Thanks for the solution! Btw, I think idx += num != 0 ? num : 0 is equivalent to idx += num, right?


  • 0
    N

    @genius1wjc you are right.


  • 2
    K

    Thanks for the solution! And for the return value, I think return idx+num == word.length() ? true : false; is just equal to return (idx+num == word.length()); so you can just cut another ternary operator.


  • 0

    Same idea:

    public boolean validWordAbbreviation(String word, String abbr) {
        int abbrCount = 0, prevChar=-1;
        for(int i = 0; i<abbr.length(); i++){
            char c = abbr.charAt(i);
            if(abbrCount==0&&c-'0'==0) return false;//in case of leading 0 notation like "01"
            if(c-'0'>=0&&c-'0'<9) abbrCount = 10*abbrCount+(c-'0');
            else{
                int checkpoint = prevChar+abbrCount+1;
                if(checkpoint>=word.length()||word.charAt(checkpoint)!=c) return false;
                prevChar = checkpoint;
                abbrCount=0; 
            }
        }//in case the last few words are abbreviated
        if(abbrCount!=0&&prevChar+abbrCount+1!=word.length()) return false;
        return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.