Monday, July 18, 2022

408. Valid Word Abbreviation

 一刷 07/2022

Version #1 Iteration

Time O(N)

Space O(1)

Runtime: 1 ms, faster than 99.55% of Java online submissions for Valid Word Abbreviation.
Memory Usage: 42.5 MB, less than 35.98% of Java online submissions for Valid Word Abbreviation.

class Solution {

    public boolean validWordAbbreviation(String word, String abbr) {

        int pw = 0, pa = 0;

        int num = 0;

        while (pw < word.length() && pa < abbr.length()) {

            while (pa < abbr.length() && Character.isDigit(abbr.charAt(pa))) {

                char c = abbr.charAt(pa);

                if (c == '0' && num == 0) {

                    return false;

                }

                num = num * 10 + (c - '0');

                pa++;

            }

            pw += num;

            num = 0;

            if (pw >= word.length() || pa >= abbr.length()) {

                break;

            }

            if (word.charAt(pw) != abbr.charAt(pa)) {

                return false;

            }

            pw++;

            pa++;

        }

        return pw == word.length() && pa == abbr.length();

    }

}

No comments:

Post a Comment