C#LeetCode刷题之#680-验证回文字符串 Ⅱ(Valid Palindrome II)
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 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 的时间复杂度为: 。
最新文章
- Resharper让我们的asp.net开发效率提高三分之一
- PHP中有关正则表达式的函数集锦
- case when then else end 用法
- Bash中的任务(job)管理
- StringBuffer and StringBuilder
- 64位Win7下编译hadoop 1.2.1问题解决
- 面向对象设计的SOLID原则
- 【百度SEO优化】如何让蜘蛛爬行你的网站
- A题笔记(7)
- Myeclipse自动生成javabean的get和set方法
- 如何成功实施SDL提供的官方Android平台Demo
- 十一、VueJs 填坑日记之使用Amaze ui调整列表和内容页面
- SQL Server 文章目录
- 吴恩达机器学习笔记54-开发与评价一个异常检测系统及其与监督学习的对比(Developing and Evaluating an Anomaly Detection System and the Comparison to Supervised Learning)
- WebRTC 学习之 概念总结
- Mysql 隐式转换
- [AHOI 2013]差异
- POJO/VO/DTO等对象模型
- ZCMU 1019: 分金币
- eg_8
热门文章
- tomcat内容总结
- Python Ethical Hacking - VULNERABILITY SCANNER(4)
- mybatis的<;if>;标签,<;foreach>;标签,<;collection>;标签,<;association>;标签以及useGeneratedKeys用法
- 记录一次JSON数据处理(省市区数据)
- Flutter防止布局溢出
- Spring葵花宝典
- 说出来也许你不信,我被 Linux 终端嘲笑了……
- Python环境那点儿事(MAC篇)
- JS的执行上下文
- 使用Gateway配置路由以及动态路由