题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

/*
整体思路:
核心:从最长的字符串截取判断是否有回文串,如果有,取其长度输出
要点:判断长度为n的字符串,是否回文,判断n-1字符串是否回文,判断n-2...
*/

//判断是否回文
function ishuiwen(str){
  for(let i=0;i<Math.floor(str.length/2);i++){
    if(str[i]!=str[str.length - i -1]){
      return false
    }
  }
  return true
}

void async function () {
    // Write your code here
    while(line = await readline()){
      let len = line.length
      let maxcount = 0,manLen = len
      let left = 0,right = manLen 
      while(left !=right){
        if(right-left<= manLen && right<=len){
          let tempStr = line.slice(left,right)
          if(ishuiwen(tempStr)){
            if(tempStr.length>maxcount){
              maxcount = tempStr.length
              console.log(maxcount)
              break;
            }
          }else{
            left++
            right++
          }
        }else{
          manLen--
          left = 0
          right = manLen
        }
      }
      console.log(1)
    }
}()

#华为机试85#
华为机试随记题解 文章被收录于专栏

华为机试随记题解

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务