Java recursion solution


  • 0
    D
    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            return validWordAbbreviation(word == null ? "" : word, 0, abbr == null ? "" : abbr, 0);
        }
        
        private boolean validWordAbbreviation(String str1, int index1, String str2, int index2) {
            if (index1 > str1.length()) {
                return false;
            }
            if (index1 == str1.length() && index2 == str2.length()) {
                return true;
            }
            if (index1 == str1.length() || index2 == str2.length()) {
                return false;
            }
            char ch2 = str2.charAt(index2);
            if (ch2 == '0') {
                return false;
            }
            if (Character.isLowerCase(ch2)) {
                return str1.charAt(index1) == ch2 ? validWordAbbreviation(str1, index1 + 1, str2, index2 + 1) : false;
            } else {
                int num = 0;
                while (index2 < str2.length() && Character.isDigit(ch2 = str2.charAt(index2))) {
                    num = num * 10 + (ch2 - '0');
                    index2++;
                }
                return validWordAbbreviation(str1, index1 + num, str2, index2);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.