LeetCode 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.
*/

public class ValidWordAbbreviation{

public static boolean isValid(String ab, String s){
int i = 0, j = 0;
while(i<s.length() && j<ab.length()){
if(s.charAt(i)==ab.charAt(j)){
i++;
j++;
continue;
}
if(ab.charAt(j)<='0' || ab.charAt(j)>'9'){
return false;
}
int num = 0;
if(Character.isDigit(ab.charAt(j))){
while(Character.isDigit(ab.charAt(j))){
num = num*10 + Character.getNumericValue(ab.charAt(j));
j++;
}
}
if(num>0){
//j+=String.valueOf(num).length();
i+=num;
}
}
return i==s.length() && j==ab.length();
}

public static void main(String[] args){
System.out.println(isValid("0ord", "word"));
}
}

No comments:

Post a Comment