1、翻转单词顺序序列
(1)问题:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
(2)代码:
class Solution:
def ReverseSentence(self, s):
l=s.split(' ')
ll=l[::-1] ##[::-1] reverse list
return ' '.join(ll)
2、Implement strStr()
(1)问题:判断一个字符串是否是另一个字符串的子串。
(2)代码:
class Solution(object):
def strStr(self, haystack, needle):
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)]==needle:
return i
return -1
3、Length of Last Word
(1)问题:最后一个单词的长度。
(2)代码:
class Solution(object):
def lengthOfLastWord(self, s):
return len(s.rstrip().split(' ')[-1])
4、Longest Palindromic Substring
(1)问题:Given a string s, find the longest palindromic substring in s.
(2)代码:
class Solution:
def longestPalindrome(self, s):
res = ""
for i in xrange(len(s)):
for k in xrange(2):
tmp = self.helper(s, i, i+k)
if len(tmp) > len(res):
res = tmp
return res
def helper(self, s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]
5、Longest Uncommon Subsequence I
(1)问题:只需要判断两字符串是否相等,如果相等就返回-1,不相等就返回较长的字符串长度。
(2)代码:
class Solution(object):
def findLUSlength(self, a, b):
if a==b:
return -1
return max(len(a),len(b))
6、Reverse String
(1)问题:反转字符串。Given s = “hello”, return “olleh”。
(2)代码:
class Solution(object):
def reverseString(self, s):
return s[::-1]
7、Valid Palindrome
(1)问题:判断是否为合法的回文字符串。验证回文子串。
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.
(2)代码:
class Solution(object):
def isPalindrome(self, s):
l,m = 0,len(s)-1
while l<m:
while l<m and not s[l].isalnum():
l+=1
while l<m and not s[m].isalnum():
m-=1
if s[l].lower()!=s[m].lower():
return False
l+=1
m-=1
return True