Two pointers, One counter in Java


  • 0
    N

    One pass through abbreviation. If it's a digit, save it for later as you may encounter a 2 after seeing a 1, and it should be treated as 12. Fail for cases when 0 appears before any other digit. Once done, check if you have reached the end of the word.

    public boolean validWordAbbreviation(String word, String abbr) {
            int prevNum = 0, idx = 0, aIdx = 0;
            while (aIdx < abbr.length()) {
                char c = abbr.charAt(aIdx);
                if (c >= '0' && c <= '9') {
                    if (prevNum == 0 && c == '0') return false; 
                    if (prevNum == 0) prevNum = c - '0';
                    else prevNum = prevNum*10+(c-'0');
                } else {
                    idx += prevNum;
                    prevNum = 0;
                    if (idx >= word.length() || c != word.charAt(idx)) return false;
                    idx++;
                }
                aIdx++;
            }
            return idx+prevNum == word.length();
        }
    

Log in to reply
 

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