Java solution using 2 pointers


  • 0
    F

    Basically 3 cases , either it is a letter and then the letter needs to be the same, or it is a number and we increment the word pointer the number of by adding adding the number to the word position or we can say the abbr is not correct.
    Finally we need to check that the both pointers are at the end of the word and the abbr respectively.

    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            
            int i = 0;
            int j = 0;
    
            while (i < word.length() && j < abbr.length()) {
                if (word.charAt(i) == abbr.charAt(j)) {
                    i++;
                    j++;
                } else if (Character.isDigit(abbr.charAt(j))) {
                    int beg = j;
                    if (abbr.charAt(beg) == '0') return false;
                    while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) {
                        j++;
                    }
                    int numChars = Integer.parseInt(abbr.substring(beg, j));
                    i += numChars;
                } else {
                    return false;
                }
    
            }
            return i == word.length() && j == abbr.length();
            
        }
    }
    

Log in to reply
 

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