CheckIO The Longest Palindromic
来源:互联网 发布:js object empty 编辑:程序博客网 时间:2024/06/15 14:38
Write a function that finds the longest palindromic substring of a given string. Try to be as efficient as possible!
If you find more than one substring you should return the one which is closer to the beginning.
Input: A text as a string.
Output: The longest palindromic substring.
Precondition: 1 < |text| ≤ 20
The text contains only ASCII characters.
解法一:
# 判断是否回文def isPalindrome(s, start, end): while start < end: if s[start] != s[end]: return False start += 1 end -= 1 return Truedef longest_palindromic(s): max, left, right = 0, 0, 0 for i in range(len(s)): j = i+1 while j < len(s): if isPalindrome(s, i, j): if (j-i+1) > max: left, right = i, j max = j - i + 1 j += 1 print (left, right, max) return s[left:right+1]
循环穷举,范围从小到大。
解法二:
# 0:9 0:8 1:9 ....def longest_palindromic(text): s = len(text) for size in range(s)[::-1]: for index in range(s - size): word = text[index:index + size + 1] if word == word[::-1]: return word同样穷举,范围从大到小。
解法三:
from itertools import combinations as Cdef longest_palindromic(text): subs = (text[start: end] for start, end in C(range(len(text) + 1), 2)) print(list(C(range(len(text) + 1), 2))) return max((s for s in subs if s == s[::-1]), key=len)其中的subs = (text[start: end] for start, end in C(range(len(text) + 1), 2))语句,直接穷举出text字符串所有的子串,此方法很python。
1 0
- CheckIO The Longest Palindromic
- checkio (Determine the order)
- 【checkio】the Moore neighbourhood
- checkio-the flat dictionary
- Three ways to solve the "Longest Palindromic Substring" problem
- Leetcode 5. Longest Palindromic Substring The Solution of Python
- checkio-the most wanted letter
- checkio the most frequent weekdays
- CheckIO The Most Wanted Letter
- checkio--
- LeetCode: Longest Palindromic Substring
- LeetCode Longest Palindromic Substring
- LeetCode: Longest Palindromic Substring
- [Leetcode] Longest Palindromic Substring
- Longest Palindromic substring
- [LeetCode] Longest Palindromic Substring
- LeetCode5:Longest Palindromic Substring
- Leetcode : Longest Palindromic Substring
- 下拉刷新 上拉加载 支持各种view
- 分布式服务框架 Zookeeper -- 管理分布式环境中的数据
- 算法:已经二叉树的前序遍历和中序遍历 写出后序遍历算法
- getNetworkInfo
- Linux进程通信之共享内存
- CheckIO The Longest Palindromic
- ios developer tiny share-20160822
- Office2013企业版23&64位官方镜像
- 图片360旋转
- python 爬虫
- opencv3.1
- 最短路径
- 各种View刷新
- Java IO BufferedInputStream和BufferedOutputStream