Easy to understand Java solution


  • 0
    A
    public class Solution {
        
        private String getDigits(String abbr, int index) {
    
            int lo = index;
    
            while (index < abbr.length()) {
                if (Character.isDigit(abbr.charAt(index))) {
                    index++;
                }
                else {
                    break;
                }
            }
            
            return abbr.substring(lo, index);
        }
        
        public boolean validWordAbbreviation(String word, String abbr) {
            
            int w=0;
            int i=0;
            
            while ( (i<abbr.length()) && (w<word.length()) ) {
                
                char ch = abbr.charAt(i);
                
                if (Character.isDigit(ch)) {
                    
                    if (ch == '0') { // check for leading characters.
                        return false;
                    }
                    
                    String digits = getDigits(abbr, i);
                    i+=digits.length();
                    w += Integer.valueOf(digits);
                    if (w > word.length()) {
                        return false;
                    }
                }
                else {
                    if (ch != word.charAt(w)) {
                        return false;
                    }
                    w++;
                    i++;
                }
                
            }
            
            return w >= word.length() && i >= abbr.length();        
        }
    }
    

Log in to reply
 

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