Java O(n+m) short straightforward solution


  • 0
    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            if (word == null || abbr == null) {
                return false;
            }   
            int i = 0;
            int j = 0;
            int start = 0;
            while (true) {
                //no leading zero, no single 0
                if (j < abbr.length() && abbr.charAt(j) == '0') {
                    return false;
                }
                
                while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) {
                    j++;
                }
                String number = abbr.substring(start, j);
                int skip = number.isEmpty() ? 0 : Integer.parseInt(number);
                i += skip;
                start = j + 1;
                if (i == word.length()) {
                    return j == abbr.length();
                } else if (i > word.length() || j >= abbr.length() || word.charAt(i) != abbr.charAt(j)) {
                    return false;
                } else {
                    i++;
                    j++;
                }
            }
        }
    }
    

Log in to reply
 

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