题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af

  • 利用扩散方法,贪心,分奇偶性讨论

  • 只关注起始值left和步长step,迭代一次就扩大一次

    class Solution {
    public:
      /**
       * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
       *
       * 
       * @param A string字符串 
       * @return int整型
       */
      int getLongestPalindrome(string A) {
          // write code here
          int n = A.size();
          int maxLen = 1;
          int step = 2;
          for(int left=0; left+step<=n; left++){
              if(judge(A.substr(left,step))){
                  maxLen = max(maxLen,step);
                  if(left>0) left-=2;
                  else left--;
                  step+=2;
              }
          }
    
          step = 3;
          for(int left=0; left+step<=n; left++){
              if(judge(A.substr(left,step))){
                  maxLen = max(maxLen,step);
                  if(left>0) left-=2;
                  else left--;
                  step+=2;
              }
          }
          return maxLen;
      }
      bool judge(string A){
          int left = 0, right = A.size()-1;
          while(left<right){
              if(A[left++]!=A[right--])
                  return false;
          }
          return true;
      }
    };
全部评论

相关推荐

04-10 08:14
门头沟学院 Java
点赞 评论 收藏
分享
xwqlikepsl:感觉很厉害啊,慢慢找
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务