1 loop concise solution


  • 0
    Z

    no nested loop, either calculate the number of chars to forward or compare char to char after forwarding

    public boolean validWordAbbreviation(String word, String abbr) {
        int lw = 0, la = 0, uw = word.length(), ua = abbr.length();
    
        int num = 0;
        while(lw < uw && la < ua) {
            char ca = abbr.charAt(la++);
            if (ca >= '0' && ca <= '9') {
                if (num == 0 && ca == '0') {return false;}
                num = num * 10 + ca - '0';
            } else {
                if ((lw += num) > uw - 1) { return false; }
                if (word.charAt(lw++) != ca) { return false; }
                num = 0;
            }
        }
    
        return lw + num == uw && la == ua;
    }

Log in to reply
 

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