前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >680. Valid Palindrome II

680. Valid Palindrome II

作者头像
ppxai
发布2023-11-18 08:30:54
1130
发布2023-11-18 08:30:54
举报
文章被收录于专栏:皮皮星球

680. Valid Palindrome II

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1:

代码语言:javascript
复制
Input: "aba"
Output: True

Example 2:

代码语言:javascript
复制
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.

Note:

  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

思路:

题目是让判断一个非空字符串在可以删除一个字符的情况下,是否是回文字符串。从贪心的角度考虑,可以发现如果一个字符串符合这种情况,一定是对于一个源串,去掉首或者尾的字符之后,剩下的字符串是回文的,因为字符串非空且只会为a-z,所以相比125题,不需要再去检验字符。

代码:

go:

代码语言:javascript
复制
func validPalindrome(s string) bool {
    i, j := 0, len(s) - 1
    for i < j {
        if s[i] != s[j] {
            return isValidPalindrome(s, i+1, j) || isValidPalindrome(s, i, j-1)
        }
        i++
        j--   
    }
    return true
}

func isValidPalindrome(s string, i, j int) bool {
    for i < j {
        if s[i] != s[j] {
            return false
        }
        i++
        j--
    }
    return true
    
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-04-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 680. Valid Palindrome II
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档