Java Solution with Comments Covering All Invalid Cases


  • 0
    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            if (word == null || abbr == null) return false;
            if (abbr.length() > word.length()) return false;
            int i = -1; // word
            int j = 0; // abbr
            int num = 0; // shift
            while (i < word.length() && j < abbr.length()) {
                char a = abbr.charAt(j);
                if (Character.isDigit(a)) {
                    num = num * 10 + a - '0';
                    if (num == 0) return false; // num could not be 0
                    if (i + num + 1 > word.length()) return false;
                    j++;
                }
                else if (a >= 'a' && a <= 'z') {
                    i += num + 1;
                    if (i >= word.length() || word.charAt(i) != a) return false;
                    // to cover first char in word, need to set i = -1 at first
                    num = 0;
                    j++;
                }
                else return false; // invaid input for abbr
            }
            return i + num + 1 == word.length();
        }
    }
    

Log in to reply
 

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