Skip to main content
Back to problems
#408
Easy Algorithms

Valid word abbreviation

Two Pointers String
37.0% acceptance
Mar 31, 2026
924
2403

No description available.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn valid_word_abbreviation(word: String, abbr: String) -> bool {
    let w = word.as_bytes();
    let a = abbr.as_bytes();
    let mut wi = 0usize;
    let mut ai = 0usize;
    while wi < w.len() && ai < a.len() {
      if a[ai].is_ascii_digit() {
        if a[ai] == b'0' {
          return false; // leading zero
        }
        let mut num = 0usize;
        while ai < a.len() && a[ai].is_ascii_digit() {
          num = num * 10 + (a[ai] - b'0') as usize;
          ai += 1;
        }
        wi += num;
      } else {
        if w[wi] != a[ai] {
          return false;
        }
        wi += 1;
        ai += 1;
      }
    }
    wi == w.len() && ai == a.len()
  }
}