Simple java code with two pointers


  • 0
    A

    Simple idea : Use two pointers to track the start of the word and abbr. Move abbr pointer, change word pointer accordingly, check whether we can get to the end of word.

    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            
            // Corner case
            if (word == null|| word.isEmpty()) {
                return (abbr == null || abbr.isEmpty());
            }
            if (abbr == null || abbr.isEmpty())
                return false;
            // Maintain two pointers of each string
            int indexAbbr = 0;
            int indexWord = 0;
            int gap = 0;
            // Move abbr pointer, change word pointer accordingly 
            while(indexAbbr < abbr.length()) {
                
                char c = abbr.charAt(indexAbbr);
                // Deal with case like word: "a", abbr: "01", that is, abbr number cannot start with 0
                if (gap == 0 && c == '0')  
                    return false;
                // If it is a digit
                if (c >= '0' && c <= '9') {
                    gap = gap * 10 + c - '0';
                    ++indexAbbr;
                    continue;
                }
                // not a digit
                else {
                    indexWord += gap;
                    gap = 0;
                    if (indexWord >= word.length()) {
                        return false;
                    } 
                    if (word.charAt(indexWord) != abbr.charAt(indexAbbr)) {
                        return false;
                    }
                    ++indexWord;
                    ++indexAbbr;
                }
            }
            indexWord += gap;
            return indexWord == word.length();
        }
    }
    
    
    

Log in to reply
 

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