Rust 力扣 - 5. 最长回文子串

文章目录

题目描述

题解思路

从中心点先寻找和中心点相等的左右端点,在基于左右端点进行往外扩散,直至左右端点不相等或者越界,然后左右端点这个范围内就是我们找寻的回文串,我们遍历中心点,就能执行上述流程就能查询所有的回文串,我们只需要取其中的最长的回文子串即可

题解代码

rust 复制代码
impl Solution {
    pub fn longest_palindrome(s: String) -> String {
        let s = s.as_bytes();

        let mut left = 0;
        let mut right = 0;
        
        let mut i = 0;

        while i < s.len() {
            let mut l = i;
            let mut r = i;

            while l > 0 && s[l - 1] == s[i] {
                l -= 1;
            }

            while r + 1 < s.len() && s[r + 1] == s[i] {
                r += 1;
            }

            let mut offset = 1;
            while l >= offset && r + offset < s.len() && s[l - offset] == s[r + offset] {
                offset += 1;
            }

            offset -= 1;

            if r - l + (offset << 1) > right - left {
                left = l - offset;
                right = r + offset;
            }

            i = r + 1;
        }

        String::from_utf8(s[left..right + 1].to_vec()).unwrap()
    }
}

题解链接

https://leetcode.cn/problems/longest-palindromic-substring/

相关推荐
是小胡嘛32 分钟前
C++之Any类的模拟实现
linux·开发语言·c++
csbysj20201 小时前
Vue.js 混入:深入理解与最佳实践
开发语言
uzong3 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
Gerardisite3 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5953 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
q***69773 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
coderxiaohan4 小时前
【C++】多态
开发语言·c++
gfdhy4 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
Warren984 小时前
Python自动化测试全栈面试
服务器·网络·数据库·mysql·ubuntu·面试·职场和发展
百***06014 小时前
SpringMVC 请求参数接收
前端·javascript·算法