Clean & readable Java solution, beats 90%


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

Log in to reply
 

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