删除一个字符验证回文字符串
最多可删一个数字判断是否是回文字符串
使用首尾夹逼比较
/** * @param {string} s * @return {boolean} */ var validPalindrome = function(s) { const length = s.length let i = 0; let j = length -1 while(i<=j&&s[i] === s[j]){ // 回文 i++; j-- } // 工具方法判断处理后是否回文 const checkFunc=(t,p)=>{ while(t<=p){ if(s[t]!==s[p]){ return false } t++; p-- } return true } // 左边的删一个 if(checkFunc(i+1,j)){ return true } // 右边的删一个 if(checkFunc(i,j-1)){ return true } // 默认false return false };
字符串匹配和添加
正则字符串匹配
字符串有add和search功能
如果不使用长度作为对象属性可能会导致超时
// 构造函数 var WordDictionary = function() { // 初始化一个对象字面量,承担 Map 的角色 this.words = {} }; /** * @param {string} word * @return {void} */ WordDictionary.prototype.addWord = function(word) { // 若该字符串对应长度的数组已经存在,则只做添加 if (this.words[word.length]) { this.words[word.length].push(word) } else { // 若该字符串对应长度的数组还不存在,则先创建 this.words[word.length] = [word] } }; /** * @param {string} word * @return {boolean} */ WordDictionary.prototype.search = function(word) { // 若该字符串长度在 Map 中对应的数组根本不存在,则可判断该字符串不存在 if (!this.words[word.length]) { return false } // 缓存目标字符串的长度 const len = word.length // 如果字符串中不包含‘.’,那么一定是普通字符串 if (!word.includes('.')) { // 定位到和目标字符串长度一致的字符串数组,在其中查找是否存在该字符串 return this.words[len].includes(word) } // 否则是正则表达式,要先创建正则表达式对象 const reg = new RegExp(word) // 只要数组中有一个匹配正则表达式的字符串,就返回true return this.words[len].some((item) => { return reg.test(item) }) }; /** * Your WordDictionary object will be instantiated and called as such: * var obj = new WordDictionary() * obj.addWord(word) * var param_2 = obj.search(word) */
atoi
/** * @param {string} s * @return {number} */ var myAtoi = function(s) { // 首先先判断边界值 const max = Math.pow(2,31) - 1 const min = -Math.pow(2,31) // 去除空格 // 直接写 const str = s.trim() // 更好的方法用正则匹配 const reg = /\s*([-\+]?[0-9]*).*/ const groups = s.match(reg) let targetNum = 0 if(groups){ // 尝试转化捕获到的结构 targetNum = +groups[1] // 注意,即便成功,也可能出现非数字的情况,比如单一个'+' if(isNaN(targetNum)) { // 不能进行有效的转换时,请返回 0 targetNum = 0 } } // 卡口判断 if(targetNum > max) { return max } else if( targetNum < min) { return min } // 返回转换结果 return targetNum };