Easy to understand Java Solution


  • 0
    M
    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            int index = 0;
            int num = 0;
            int wordPointer = 0;
            while(index < abbr.length() && wordPointer < word.length() ){
                System.out.println("word reaches index " + wordPointer + " and abbr reaches index " + index + ".");
                if(Character.isDigit(abbr.charAt(index))){
                    while(index < abbr.length() && Character.isDigit(abbr.charAt(index))){
                        num = num * 10 + (abbr.charAt(index) - '0');
                        if(num == 0){
                            return false;
                        }
                        index++;
                    }
                    System.out.println("abbr reaches index " + index +  " get number " + num + ".");
                    if(index == abbr.length()){
                        if((word.length() - wordPointer) != num){
                            return false;
                        }
                    }
                    for(int i = 0; i < num; i++){
                        wordPointer++;
                        if(wordPointer == word.length() && i != num - 1){
                            return false;
                        }
                    }
                    
                    System.out.println("update word's index to " + wordPointer +  " to match the abbr.");
    
                }else{
                    num = 0;
                    System.out.println("check if word 's char at "  + wordPointer + " matches abbr's char at " + index + ".");
    
                    if(word.charAt(wordPointer) != abbr.charAt(index)){
                        return false;
                    }
                    index++;
                    wordPointer++;
                }
            }
            return index == abbr.length() && wordPointer == word.length();
        }
    }

Log in to reply
 

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