125. 验证回文串

思路

先做正则将不符合的字符去掉,再从两端对比

代码

  1. /**
  2. * @param {string} s
  3. * @return {boolean}
  4. */
  5. var isPalindrome = function(s) {
  6. s = s.replace(/[^a-zA-Z0-9]/g, '')
  7. let left = 0, right = s.length - 1;
  8. while(left < right) {
  9. let slow = s[left].toLowerCase(), fast = s[right].toLowerCase()
  10. if (slow !== fast) {
  11. return false
  12. }
  13. left++;
  14. right--;
  15. }
  16. return true
  17. };

复杂度分析

时间复杂度 回文串的定义 - 图1#card=math&code=O%28N%29)
空间复杂度 回文串的定义 - 图2#card=math&code=O%281%29)