Given anon-emptystringsand an abbreviationabbr, return whether the string matches with the given abbreviation.

A string such as"word"contains only the following valid abbreviations:

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

Notice that only the above abbreviations are valid abbreviations of the string"word". Any other string is not a valid abbreviation of"word".

Note:
Assumescontains only lowercase letters andabbrcontains only lowercase letters and digits.

class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        if(word == null && abbr == null)
            return true;
        if(word == null || abbr == null)
            return false;

        int a = 0;
        int w = 0;

        while(a < abbr.length()) {
            if(w >= word.length())
                return false;

            char c = abbr.charAt(a);

            if(c >= 'a' && c <= 'z') {
                if(c != word.charAt(w))
                    return false;

                a++;
                w++;
            } else {
                StringBuilder sb = new StringBuilder();
                while(a < abbr.length() && abbr.charAt(a) >= '0' && abbr.charAt(a) <= '9') {
                    sb.append(abbr.charAt(a));
                    a++;
                }

                if(!valid(sb.toString())) 
                    return false;

                int len = Integer.parseInt(sb.toString());
                if(w + len > word.length())
                    return false;

                w += len;
            }
        }

        return w == word.length();
    }

    public boolean valid(String s) {
        if(s.charAt(0) == '0' && s.length() > 1)
            return false;
        if(s.equals("0"))
            return false;
        return true;
    }
}

results matching ""

    No results matching ""