Short JAVA solution that beats 95%


  • 0
    Y
    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            int ptr = 0;
            int number = 0;
            for (char c : abbr.toCharArray()) {
                if (c >= 'a') {
                    ptr += number;
                    number = 0;
                    if (ptr >= word.length() || c != word.charAt(ptr))
                        return false;
                    ptr++;
                } else {
                    if (number == 0 && c == '0')
                        return false;
                    number = number * 10 + (c - '0');
                }
            }
            return ptr == word.length() - number;
        }
    }
    

    By the way I think Stefan's regex solution is so smart. I wish I can be that smart some day


Log in to reply
 

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