LeetCode学习(5)Shortest Palindrome(最短回文串)
2017-10-21 20:55
495 查看
1.问题描述
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given “aacecaaa”, return “aaacecaaa”.
Given “abcd”, return “dcbabcd”.
给定一个字符串,在字符串的前面加入字符,将该字符串变成一个最短的回文字符串,如题目中所示aacecaaa变成最短的回文只需要在前面加上字符a ,得到回文字符串aaacecaaa
2.代码时刻
3.测试结果
测试用例: s = “xixl”
测试结果: s=”lxixil”
测试用例: s = “aaacaaafigh”
测试结果: s = “hgifaaacaaafigh”
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given “aacecaaa”, return “aaacecaaa”.
Given “abcd”, return “dcbabcd”.
给定一个字符串,在字符串的前面加入字符,将该字符串变成一个最短的回文字符串,如题目中所示aacecaaa变成最短的回文只需要在前面加上字符a ,得到回文字符串aaacecaaa
2.代码时刻
//c++ VS2013 #include<iostream> #include<string> using namespace std; bool Check(string s, int low, int high) { //该函数主要判断从low到high的字符串是否为回文字符串 if (low == high) return true; while (low<high) { if (s[low] != s[high]) return false; low++; high--; } return true; } string ShortestPalindrome(string s) { int i, j; int len; string result = ""; len = s.length() - 1; if (len <= 0) return ""; for (len; len>0; len--) //从输入的字符串最后一位开始往前找,找到满足回文的最大回文字符串 { if (s[0] == s[len] && Check(s, 0, len)) break; } /*找到第1-len位表示最长的回文串,第(len+1)-length()位就是没有匹配上的,反转第(len+1)-length()位并加在原来字符串最前面就是*/ for (i = s.length() - 1; i>len; i--) result += s[i]; result += s; return result; } int main() { string s = "xixl"; string a = ShortestPalindrome(s); cout<<a << endl; return 0; }
3.测试结果
测试用例: s = “xixl”
测试结果: s=”lxixil”
测试用例: s = “aaacaaafigh”
测试结果: s = “hgifaaacaaafigh”
相关文章推荐
- [LeetCode] 214. Shortest Palindrome 最短回文串
- [LeetCode] Shortest Palindrome 最短回文串
- Leetcode Shortest Palindrome (最短回文串)
- [LeetCode] Shortest Palindrome 最短回文串
- Leetcode算法学习日志-122 Best Time to Buy and Sell Stock II
- jiler的LeetCode学习笔记 java版本Median of Two Sorted Arra
- Python 爬虫学习:爬取LeetCode的题目并且按照难度分类
- LeetCode 336 Palindrome Pairs(回文串)
- leetcode_234. Palindrome Linked List 判断单链表是否为回文串,快慢指针法找中间节点,反转单链表
- LeetCode 214. Shortest Palindrome(最短回文)
- LeetCode学习篇二十七——Maximum Subarray
- LeetCode编程练习 - Reverse Vowels of a String学习心得
- Leetcode代码学习周记——Add Two Nmubers
- python学习——leetcode第五题 Longest Palindromic Substring
- 并行算法学习之单源最短路径
- LeetCode 学习笔记:Question 1、Two Sum
- LeetCode 581. Shortest Unsorted Continuous Subarray (最短无序连续子数组)
- 算法面试题-leetcode学习之旅(二)
- Leetcode学习(6)—— Reverse Words in a String III
- [LeetCode] 409. 最长回文串