首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我需要写困难的回文

我需要写困难的回文
EN

Stack Overflow用户
提问于 2021-04-08 14:34:08
回答 5查看 116关注 0票数 0

这就是我的例子。字符串是给定的。实现一个函数- detectPalindrom,它可以检测回文字符串。

给出的参数不是字符串-返回‘传递的参数不是字符串’。

  • 给定的字符串是空的-返回'String是空的‘。
  • 给定的字符串回文-返回’这个字符串不是回文-返回‘这个字符串不是回文!’

我写了一个解决方案,但效果不正确:

代码语言:javascript
运行
复制
 const detectPalindrome = (str) => {
    const palindr = str.split('').reverse().join('')

    if(str === '') {
      return 'String is empty'
  } 
    if (str === palindr) {
       return 'This string is palindrome!'
   } 
    if (str !== palindr) {
       return 'This string is not a palindrome!'
   }
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2021-04-08 14:43:21

只需在创建palindr字符串之前进行检查即可。

代码语言:javascript
运行
复制
const detectPalindrome = (str) => {
  if (typeof str !== "string") {
    return 'Passed argument is not a string'
  }
  
  const palindr = str.split('').reverse().join('');

  if (str === '') {
    return 'String is empty';
  }
  if (str === palindr) {
    return 'This string is palindrome!';
  }
  if (str !== palindr) {
    return 'This string is not a palindrome!';
  }
};

detectPalindrome("154");

票数 1
EN

Stack Overflow用户

发布于 2021-04-08 14:47:56

您需要通过只保留非空白字符来转义输入。你也可以把它细化,去掉一些特殊的字符。

代码语言:javascript
运行
复制
const
  reverse = str => str.split('').reverse().join(''),
  escape = str => str.toLowerCase().replace(/[^\S]|[,;\.?!'"]/g, '');

const detectPalindrome = input => {
  if (typeof input === 'string') {
    if (input === '') return 'String is empty'
    const
      str = escape(input),
      pal = reverse(str);
    return str === pal
      ? 'This string is a palindrome!'
      : 'This string is not a palindrome!';
  } else {
    return 'Passed argument is not a string';
  }
}

console.log(detectPalindrome(0));         // 'Passed argument is not a string'
console.log(detectPalindrome(''));        // 'String is empty'
console.log(detectPalindrome('Racecar')); // 'This string is a palindrome!'
console.log(detectPalindrome('Apple'));   // 'This string is not a palindrome!'

console.log(detectPalindrome("Madam I'm Adam")); // TRUE

票数 0
EN

Stack Overflow用户

发布于 2021-04-08 14:48:39

代码语言:javascript
运行
复制
const detectPalindrome = (str) => {

  if (typeof str !== 'string')
    return 'Passed argument is not a string'

  const palindr = str.split('').reverse().join('')

  if (str === '') {
    return 'String is empty'
  }
  if (str === palindr) {
    return 'This string is palindrome!'
  }
  if (str !== palindr) {
    return 'This string is not a palindrome!'
  }
}

console.log(detectPalindrome(123))
console.log(detectPalindrome(""))
console.log(detectPalindrome("abcd"))
console.log(detectPalindrome("lol"))

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67006220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档