408. Valid Word Abbreviation

Given a non-empty string s and an abbreviation abbr, 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:
Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

Example 1:

Given s = "internationalization", abbr = "i12iz4n":

Return true.

Example 2:

Given s = "apple", abbr = "a2e":

Return false.

Rust Solution

struct Solution;

impl Solution {
    fn valid_word_abbreviation(word: String, abbr: String) -> bool {
        let mut i = 0;
        let mut j = 0;
        let n = word.len();
        let m = abbr.len();
        let word: Vec<char> = word.chars().collect();
        let abbr: Vec<char> = abbr.chars().collect();
        while i < n && j < m {
            if abbr[j].is_alphabetic() {
                if word[i] != abbr[j] {
                    return false;
                }
                i += 1;
                j += 1;
            } else {
                let mut v = 0;
                while j < m && abbr[j].is_numeric() {
                    if v == 0 && abbr[j] == '0' {
                        return false;
                    }
                    v *= 10;
                    v += (abbr[j] as u8 - b'0') as usize;
                    j += 1;
                }
                i += v;
            }
        }
        i == n && j == m
    }
}

#[test]
fn test() {
    let word = "internationalization".to_string();
    let abbr = "i12iz4n".to_string();
    assert_eq!(Solution::valid_word_abbreviation(word, abbr), true);
    let word = "apple".to_string();
    let abbr = "a2e".to_string();
    assert_eq!(Solution::valid_word_abbreviation(word, abbr), false);
}

Having problems with this solution? Click here to submit an issue on github.