408. Valid Word Abbreviation (two pointers)

T:O(m)

S: O(1)

// T:O(m), S: O(1)
class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        int i = 0;
        int j = 0;
        int m = word.length();
        int n = abbr.length();
        
        while (i < m && j < n) {
            // if abbr between 0~9, cal the number(maybe over 10, so needs calculate the offset)
            if (abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') {
                
                if (abbr.charAt(j) == '0') {
                    return false;
                }
                
                int val = 0;
                while (j < n && abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') {
                    val = val*10 + (abbr.charAt(j++) - '0');
                }
                i += val; // add offset to word index i
                
            } else  if (word.charAt(i++) != abbr.charAt(j++)) { // one by one compare
                return false;
            }
        }
        return i == m && j == n;
    }
}

Last updated