Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

408. Valid Word Abbreviation #147

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public boolean validWordAbbreviation(String word, String abbr) { if (word == null || abbr == null) return false; if (abbr.length() > word.length()) return false; int i = -1; int j = 0; int num = 0; while(i < word.length() && j < abbr.length()) { char a = abbr.charAt(j); if (Character.isDigit(a)) { num = num *10 + (a - '0'); if (num == 0) return false; // num could not be 0 if (i + num + 1 > word.length()) return false; j++; } else if(a >= 'a' && a <= 'z') { i += num + 1; if (i >= word.length() || word.charAt(i) != a) return false; // to cover first char in word, need to set i = -1 at first num = 0; j++; } else return false; // invaid input for abbr } return i + num + 1 == word.length(); } }


Solution2

public boolean validWordAbbreviation(String word, String abbr) { int wLength=word.length(),aLength=abbr.length(),curNum=0,index=0; if(wLength==0||aLength==0) return false; for(int i=0;i<aLength;i++){ char temp=abbr.charAt(i); if(temp<='9'&&temp>='0'){ if(curNum==0&&temp=='0') return false; //This catches some edge case like "a01t" curNum=curNum*10+(int)(temp-'0'); }else{ index=index+curNum; if(index>=wLength||word.charAt(index)!=temp) return false; index++; curNum=0; } } if(index+curNum!=wLength) return false; //Make sure both abbr and word reach the end. return true; }

Shawngbk commented 7 years ago

google