Java Accepted Solution Using Regular Expression


  • 0
    A
    public boolean validWordAbbreviation(final String word, final String abbreviation) {
            StringBuffer regexBuffer = new StringBuffer();
            
            for (int i = 0; i < abbreviation.length(); i++) {
                if (Character.isDigit(abbreviation.charAt(i))) {
                    if (Character.getNumericValue(abbreviation.charAt(i)) == 0) {// number should not start with 0
                        return false;
                    }
    
                    int times = 0;
                    while (i < abbreviation.length() && Character.isDigit(abbreviation.charAt(i))) {
                        times = 10 * times + Character.getNumericValue(abbreviation.charAt(i));
                        i++;
                    }
                    i--;
    
                    if (times > 0) {
                        regexBuffer.append("[a-z]{" + times + "}");
                    }
                } else {
                    regexBuffer.append(abbreviation.charAt(i));
                }
            }
    
            return word.matches(regexBuffer.toString());
        }
    

Log in to reply
 

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