LeetCode OJ ---- Longest Palindromic Substring
2016-03-04 18:19
363 查看
题目描述
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.code(c++)
class Solution { public: string longestPalindrome(string s) { size_t len = s.size(); int pre = 0; int cur = 1; int next = 2; size_t max_length = 1; size_t begin = pre; if (len < 2) return s; if (len == 2) return s[pre] == s[cur] ? s : s.substr(pre,1); while((cur != len && next != len)){ size_t length = 0; if(s[pre] != s[cur] && s[pre] != s[next]){ ++pre; ++cur; ++next; } else{ int sameEleNum = 0; if(s[pre] == s[cur]){ int count = cur + 1; sameEleNum = 2; while(count != len && s[pre] == s[count]){ ++sameEleNum; ++count; } } size_t breakPoint = pre; if(sameEleNum != 0){ --pre; cur += sameEleNum - 1; length += sameEleNum; while(pre >= 0 && cur != len && s[pre] == s[cur]){ length += 2; --pre; ++cur; } if(length > max_length){ max_length = length; begin = pre + 1; } } else{ --pre; ++next; length += 3; while(pre >= 0 && next != len && s[pre] == s[next]){ length += 2; --pre; ++next; } if(length > max_length){ max_length = length; begin = pre + 1; } } pre = breakPoint + 1; cur = pre + 1; next = cur + 1; } if(next == len && s[pre] == s[cur]){ if(max_length < 2){ max_length = 2; begin = pre; } } } return s.substr(begin, max_length); } };
note:
要注意回文字符中间是否有连续相等的元素,有与没有会有不同的处理方法相关文章推荐
- R语言数据挖掘资料
- leetcode笔记:Bitwise AND of Numbers Range
- static const vs. extern const
- ubuntu中的sources.list文件
- Win 8.1/10 如何设置以Administrator身份启动cmd
- Android Studio 上传SVN标准全过程
- HTTPS科普扫盲帖
- HDU 1213 - How Many Tables
- 属性动画
- jquery的ajax同步和异步
- 框架汇总
- POJ 1611 - The Suspects
- 数字游戏
- C++中类所占内存空间的分析(转载)
- ASP.NET分页控件
- 学习进度01
- PM 与 LM 如何分钱问题
- 关于随机数的产生
- An instance of “(null)” is already running. Choose “Stop” to terminate and launch a new instance.
- Linux 后台进程与守护进程