Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

判断给定的字符串是否是回文 #7

Open
MY729 opened this issue Jul 19, 2019 · 0 comments
Open

判断给定的字符串是否是回文 #7

MY729 opened this issue Jul 19, 2019 · 0 comments

Comments

@MY729
Copy link
Owner

MY729 commented Jul 19, 2019

题目

判断给定的字符串是否是回文

例如:

字符串 "上海自来水来自海上" 是回文
字符串 "abba" 是回文
字符串 "abca" 不是回文

解析

  1. 取头部和尾部的字符对比是否相同
  2. 取正数第二个和倒数第二个字符对比是否相同
  3. 取正数第三个和倒数第三个字符对比是否相同
  4. 重复上面的步骤直到取到最中间的数
  5. 上面步骤中只要存在一个不相同,那么这个字符串就不是回文

答案

let isBackStr = str => {
  let len = str.length
  let isTargetStr = true
  for(let i = 0; i < len; i++) {
    if(str[i] !== str[len - i - 1]) {
      isTargetStr = false
    }
  }
  return isTargetStr
}

执行结果:

isBackStr('上海自来水来自海上') // 调用
// 输出
true

isBackStr('abba') // 调用
// 输出
true

isBackStr('abca') // 调用
// 输出
false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant