Java solution, iterating over abbr and jumping word

  • 0

    Following is my solution in Java.

    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            char[] wordChars = word.toCharArray();
            char[] abbrChars = abbr.toCharArray();
            int w=0, a=0;
            while (a<abbrChars.length && w<wordChars.length){
                // if numeric, we read the value N and then skip N characters in word
                // however, 'number' starting with 0 is not valid; this logic is handled in else
                if(Character.isDigit(abbrChars[a]) && '0'!=abbrChars[a]){
                    int skip = 0;
                    while (a<abbrChars.length && Character.isDigit(abbrChars[a])){
                        skip = skip*10+abbrChars[a]-'0';
                } else {
                        //short circuit
                        return false;
            // if a match then both indices should reach their respective ends
            return w==wordChars.length && a==abbrChars.length;

Log in to reply

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