回溯 classSolution{ fun isMatch(s: String, p: String): Boolean { val sLen = s.length val pLen = p.length var sIdx = 0 var pIdx = 0 var starIdx = -1 var sTmpIdx = -1
while (sIdx < sLen) { // If the pattern caracter = string character // or pattern character = '?' if (pIdx < pLen && (p[pIdx] == '?' || p[pIdx] == s[sIdx])) { ++sIdx ++pIdx } elseif (pIdx < pLen && p[pIdx] == '*') { // Check the situation // when '*' matches no characters starIdx = pIdx sTmpIdx = sIdx ++pIdx } elseif (starIdx == -1) { returnfalse } else { // Backtrack: check the situation // when '*' matches one more character pIdx = starIdx + 1 sIdx = sTmpIdx + 1 sTmpIdx = sIdx }// If pattern character != string character // or pattern is used up // and there was '*' character in pattern before // If pattern character != string character // or pattern is used up // and there was no '*' character in pattern // If pattern character = '*' }
// String is used up, and the remaining characters in the pattern should all be '*' characters for (i in pIdx until pLen) if (p[i] != '*') returnfalse returntrue }