const isMatch = (str, pattern) => {
if (!str || !pattern) return false;
return handleMatch(str, 0, pattern, 0);
}
const handleMatch = (str, sIndex, pattern, pIndex) => {
if (sIndex === str.length && pIndex === pattern.length) return true;
if (sIndex !== str.length && pIndex === pattern.length) return false;
if (pIndex < pattern.length - 1 && pattern[pIndex + 1] === '*') {
if (sIndex < str.length && (str[sIndex] === pattern[pIndex] || pattern[pIndex] === '.')) {
return handleMatch(str, sIndex, pattern, pIndex + 2) ||
handleMatch(str, sIndex + 1, pattern, pIndex + 2) ||
handleMatch(str, sIndex + 1, pattern, pIndex);
} else {
return handleMatch(str, sIndex, pattern, pIndex + 2);
}
}
if (sIndex < str.length && (str[sIndex] === pattern[pIndex] || pattern[pIndex] === '.')) {
return handleMatch(str, sIndex + 1, pattern, pIndex + 1);
}
return false;
}
对字符串数据结构常见的算法进行总结,也为了更好滴应对后面深入学习算法。
表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
例如:字符串‘+100’、‘5e2’都表示数值,但是12e、1a3.14、1e+4.3就不是数值。
答案
考虑所有情况。
正则表达式匹配
请实现一个函数用来匹配包括.和*的表达式。
其中.表示任意一个字符,而*表示它前面的字符可以出现任意次(包括0次)。
答案
字符串的全排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。
例如输入字符串abc,则其全排列的所有字符串为:abc,acb,bac,bca,cab,cba。
答案