This is two points problem, just concentrate and carefully deal with the characters, then the problem can be solved.
This is a very good problem for writing all kinds of edge test cases.
public boolean validWordAbbreviation(String word, String abbr) { int m = word.length(), n = abbr.length(); int i = 0, j = 0; while (i < m && j < n) { if (word.charAt(i) == abbr.charAt(j)) { i++; j++; } else { if (!Character.isDigit(abbr.charAt(j)) || abbr.charAt(j) == '0') return false; else { int start = j; while (j < n && Character.isDigit(abbr.charAt(j))) { //be careful, need ot add a j < n, otherwise, eg. abbr="a1" will fail j++; } int len = Integer.valueOf(abbr.substring(start, j)); i += len; } } } return i == m && j == n; //if simply return true, eg. word = "a", abbr="2" will fail }
Or we can handle the nums this way:
public boolean validWordAbbreviation(String word, String abbr) { int i=0, j=0; int num = 0; while(i<word.length() && j<abbr.length()){ if(word.charAt(i)==abbr.charAt(j)){ i++; j++; } else{ if (!Character.isDigit(abbr.charAt(j))||abbr.charAt(j)=='0') return false; else { while(j<abbr.length() && Character.isDigit(abbr.charAt(j))){ num = num*10+abbr.charAt(j)-'0'; //don't forget to minus '0' to convert a char to an int j++; } i+=num; num=0; //don't forget to change num = 0 after using. } } } return i==word.length() && j==abbr.length(); }