问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3961 访问。

给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。

输入: "aba"

输出: True

输入: "abca"

输出: True

解释: 你可以删除c字符。

注意:字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。


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

Input: "aba"

Output: True

Input: "abca"

Output: True

Explanation: You could delete the character 'c'.

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


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3961 访问。

public class Program {

    public static void Main(string[] args) {
var s = "abca"; var res = ValidPalindrome(s);
Console.WriteLine(res); s = "Iori's Blog!"; res = ValidPalindrome2(s);
Console.WriteLine(res); Console.ReadKey();
} private static bool ValidPalindrome(string s) {
//暴力解法,超时未AC
if(IsPalindrome(s)) return true;
for(int i = 0; i < s.Length; i++) {
var substring = s.Remove(i, 1);
if(IsPalindrome(substring)) return true;
}
return false;
} private static bool IsPalindrome(string s) {
//前后双指针法
var i = 0;
var j = s.Length - 1;
while(i < j) {
if(s[i] != s[j]) return false;
i++;
j--;
}
return true;
} public static bool ValidPalindrome2(String s) {
var i = -1;
var j = s.Length;
while(++i < --j)
//不相同时,并不代表就不是回文了,因为有删除一个字符的机会
//但我们不知道往前删除还是往后删除
//所以我们前后各判定一次
if(s[i] != s[j])
return IsPalindrome2(s, i, j - 1) || IsPalindrome2(s, i + 1, j);
return true;
} private static bool IsPalindrome2(String s, int i, int j) {
while(i < j) if(s[i++] != s[j--]) return false;
return true;
} }

以上给出2种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3961 访问。

True
False

分析:

显而易见,ValidPalindrome 的时间复杂度为:  ,ValidPalindrome2 的时间复杂度为:  。

最新文章

  1. Resharper让我们的asp.net开发效率提高三分之一
  2. PHP中有关正则表达式的函数集锦
  3. case when then else end 用法
  4. Bash中的任务(job)管理
  5. StringBuffer and StringBuilder
  6. 64位Win7下编译hadoop 1.2.1问题解决
  7. 面向对象设计的SOLID原则
  8. 【百度SEO优化】如何让蜘蛛爬行你的网站
  9. A题笔记(7)
  10. Myeclipse自动生成javabean的get和set方法
  11. 如何成功实施SDL提供的官方Android平台Demo
  12. 十一、VueJs 填坑日记之使用Amaze ui调整列表和内容页面
  13. SQL Server 文章目录
  14. 吴恩达机器学习笔记54-开发与评价一个异常检测系统及其与监督学习的对比(Developing and Evaluating an Anomaly Detection System and the Comparison to Supervised Learning)
  15. WebRTC 学习之 概念总结
  16. Mysql 隐式转换
  17. [AHOI 2013]差异
  18. POJO/VO/DTO等对象模型
  19. ZCMU 1019: 分金币
  20. eg_8

热门文章

  1. tomcat内容总结
  2. Python Ethical Hacking - VULNERABILITY SCANNER(4)
  3. mybatis的&lt;if&gt;标签,&lt;foreach&gt;标签,&lt;collection&gt;标签,&lt;association&gt;标签以及useGeneratedKeys用法
  4. 记录一次JSON数据处理(省市区数据)
  5. Flutter防止布局溢出
  6. Spring葵花宝典
  7. 说出来也许你不信,我被 Linux 终端嘲笑了……
  8. Python环境那点儿事(MAC篇)
  9. JS的执行上下文
  10. 使用Gateway配置路由以及动态路由