通过反转子串找到最长的回文

时间:2018-03-19 23:00:55

标签: javascript algorithm

我试图找到最长的回文。我从字符串的第一个字母开始有两个指针。对于外循环中的每个字母,我遍历内循环中的所有其他字母并使用子字符串,即起始字母(外循环)和结束字母(内循环)之间的差异。我反转这个子字符串并检查反转版本是否与原始版本相同。有了这个,我知道我找到了一个回文。这个算法适用于我的大多数测试用例,除了一个,我无法弄清楚原因。



function longestPalindrome (str) {
  const string = str.toLowerCase();
  if (str.length < 2) return null;
  let palindrome = '';

  function stringReverser (start, end) {
    const reversed = string.substr(start, end).split('').reverse().join('');
    return reversed;
  }

  for (let i = 0; i <= string.length; i++) {
    for (let j = i; j <= string.length; j++) {
      if (string.substr(i, j) === stringReverser(i, j)) {
        if (string.substr(i,j).length > palindrome.length) {
          palindrome = string.substr(i,j);
        }
      }
    }
  }

  if (!palindrome) return null;
  return palindrome;
}

let result1 = longestPalindrome('My mom is called annnna')
let result2 = longestPalindrome('My dad is a racecar athelete')
let result3 = longestPalindrome('That trip with a kayak was quite an adventure!')

console.log(result1)
console.log(result2)
console.log(result3)// should return ' kayak ' but returns 't t' instead.
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:2)

我建议抽象出所选的子字符串,并使用20130601函数:

concat(year,'0',quarter*3,'01') as Date

答案 1 :(得分:1)

原始实现中的错误是substr参数是(begin, length),其中原始代码似乎对第二个参数的含义有错误的假设。见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

以下是对示例代码的一个小改动,它具有更正确的输出:

&#13;
&#13;
function longestPalindrome (str) {
  const string = str.toLowerCase();
  if (str.length < 2) return null;
  let palindrome = '';

  function stringReverser (start, length) {
    const reversed = string.substr(start, length).split('').reverse().join('');
    return reversed;
  }

  for (let i = 0; i < string.length; i++) {
    for (let j = 1; j <= string.length - i; j++) {
      if (string.substr(i, j) === stringReverser(i, j)) {
        if (j > palindrome.length) {
          palindrome = string.substr(i,j);
        }
      }
    }
  }

  if (!palindrome) return null;
  return palindrome;
}

let result1 = longestPalindrome('My mom is called annnna')
let result2 = longestPalindrome('My dad is a racecar athelete')
let result3 = longestPalindrome('That trip with a kayak was quite an adventure!')

console.log(result1)
console.log(result2)
console.log(result3)// should return ' kayak ' but returns 't t' instead.
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是使用数组助手的解决方案。回文辅助函数检查给定的单词是否是回文。过滤器查找返回true的那些,然后使用reduce查找最长的回文。

function findLongest(str) {
  let arr = str.split(' ').filter(word => palindrome(word));
  return arr.reduce((a,b) => a.length > b.length ? a : b);
}

function palindrome(str) {
    return str === str.split('').reverse().join('');
}

console.log(findLongest('That trip with a kayak was quite an adventure!'));

答案 3 :(得分:0)

Java代码

&#34; findlongestPalindrome&#34; function将参数作为字符串并返回最长的回文字符串

&#34; isPalindrome&#34;验证字符串是否为回文

public class findlongestPalindrome {

      public static void main(String[] args) {
          System.out.println("-->" + findlongestPalindrome("That trip with a kayak was quite an adventure!"));
      }
      public static String findlongestPalindrome(String s){
          StringBuffer sb = new StringBuffer();
          int len = 0;
          int maxlen = 0;
          String maxString = "";

          char[] arr = s.toCharArray();
          for(int i=0;i<=s.length();i++){
              for(int j=i;j<s.length();j++){
                  System.out.print(arr[j]);
                  sb.append(arr[j]);
                  if(isPalindrome(sb.toString())) {
                      len = sb.toString().length();
                      if(len > maxlen) {
                          maxlen = len;
                          maxString = sb.toString() + "";
                      }
                  }
              }
              sb = new StringBuffer();
              System.out.println();
          }
          return maxString;
      }
      public static boolean isPalindrome(String s){
          StringBuffer sb = new StringBuffer(s);
          return sb.reverse().toString().equals(s);
      }

}