题解 | #最长回文子串#

最长回文子串

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

#两层循环,暴力破解
while True:
    try:
        s = input()
        res = []
        
        for i in range(len(s)):
            for j in range(i+1, len(s)+1):
                if s[i:j] == s[i:j][::-1]:
                    res.append(j-i)
        if res != '':
            print(max(res))
    except:
        break
#另一种方法:
while True:
    try:
        s = input()   #输入
        len_s = len(s)  
        result=0   #初始化最后的结果
        for n in range(len_s):   #从第一个字符开始搜索最长的字符串
            max_length = result+1  #max_length代表搜索字符串的长度,所以只搜索大于result的字符串
            while n+max_length<=len_s:  #代表搜索完以第n+1个字符串开头的所有字符串
                if s[n:n+max_length] == s[n:n+max_length][::-1]:  #如果满足是回文字符串
                     result = max_length   #则此时最大的字符串长度变为max_length
                max_length +=1   #每次增加字符串的长度1
        if result !=0:   #防止空字符串
            print(result)
    except:
        break

全部评论

相关推荐

点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
07-01 17:14
中北大学 Java
兄弟们是真是假
牛客46374834...:我在boss上投java岗从来没成功过
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务