Valid Word Abbreviation

LintCode Q 637 - Valid Word Abbreviation

Given a non-empty string word 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"]

Solution

This is a String matching question, we can use two pointers method.
Be careful about boundary cases. For example:
the char is '0';

Code:

public boolean validWordAbbreviation(String word, String abbr) {
	if (word.length() != abbr.length()) return false;
	int i = 0, j = 0;
	while (i < word.length() && j < abbr.length()) {
		if (Character.isLetter(abbr.charAt(j))) {
			if (word.charAt(i++) != abbr.charAt(j++)) return false;
		} else {
			if (abbr.charAt(j) == '0') return false;
			
			int num = 0;
			while (j < abbr.length() && abbr.charAt(j)) {
				num = num * 10 + abbr.charAt(i) - '0'; j++;
			}
			
			i += num;
		}
	}

	return i == word.length() && j == abbr.length();
}

   Reprint policy


《Valid Word Abbreviation》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC