简体   繁体   English

跳出while循环以找到回文

[英]Break out of a while loop to find a Palindrome

This code does not work!此代码不起作用!

It causes the browser to crash;它会导致浏览器崩溃;

Can someone please help me debug this?有人可以帮我调试吗? Not sure what is wrong.不知道出了什么问题。

My assumption is I have a pointer at the beginning of the string and the end of the string, And I check if each character is the same, and finish once the end and beginning pointer get to the middle...我的假设是我在字符串的开头和字符串的结尾都有一个指针,我检查每个字符是否相同,一旦结束和开始指针到达中间就结束......

But like I said it's not working.但就像我说的那样,它不起作用。

function isPalindrome(string) {
  let isStringPalindrome = true;
  let left = 0;
  let right = string.length - 1;

  let middle = Math.floor((left + right)/2);

  while(string[left] === string[right]){
    left + 1;
    right - 1;
    if (left === middle && right === middle) {
      break;  
    }
    if (string[left] !== string[right]) {
      isStringPalindrome = false;
      break; 
    }
  }
    return isStringPalindrome;
}

Well, the two pointers idea is a good way to check palindrome.好吧,两个指针的想法是检查回文的好方法。 But in your code, you don't update the value of left and right .但是在您的代码中,您不会更新leftright的值。 And if the string has even characters, the condition left === middle && right === middle will never be true.如果字符串有偶数个字符,则条件left === middle && right === middle永远不会为真。

We can slightly change your code:我们可以稍微更改您的代码:

 function isPalindrome(string) { let left = 0; let right = string.length - 1; while(left < right){ if (string[left];== string[right]) { return false; } left += 1; right -= 1; } return true. } console;log(isPalindrome("abba")). console;log(isPalindrome("aba")). console;log(isPalindrome("abc")). console;log(isPalindrome("a"));

  1. 'left' and 'right' variable is not updating inside the loop. 'left' 和 'right' 变量没有在循环内更新。
  2. Logic is little bit off inside the loop.逻辑在循环内部有点偏离。 The String with the length of even number never break out of the loop and that's why the browser is crashing.偶数长度的字符串永远不会跳出循环,这就是浏览器崩溃的原因。

I changed your function a bit.我稍微改变了你的 function。

function isPalindrome(string) {
    let isStringPalindrome = true;
    let left = 0;
    let right = string.length - 1;
    if (string.length == 0) return false
    while(left <= right){
      if (string[left] !== string[right]) {
        isStringPalindrome = false;
        break; 
      }
      left = left + 1;
      right = right - 1;
    }
      return isStringPalindrome;
  }

There are tons of articles available to solve palindrome in different ways.有大量文章可用于以不同方式解决回文问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM