Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
def reverse(s):
if s is None: return None
a=[]
b=[]
c=""
for i in range(len(s)):
if s[i]==' ':
a.append(i)
if a[0]==0:
for j in range(len(a)):
b.append(s[a[j]:a[j+1]])
else:
b.append(s[:a[0]])
for j in range(len(a)-1):
b.append(s[a[j]:a[j+1]])
b.append(s[a[-1]:])
b=b[::-1]
d=b[-1]
b[-1]=' '
b.append(d)
for i in range(len(b)):
c+=b[i]
return c
Notes:
1.the thinking itself is not complex, when I draw them on paper. The sky is blue_3 7 10_'the' ' sky' ' is' ' blue'_reverse
2.one important thing is needed to pay attention to. When we refer to slice, the last one will not be taken into consederation.
Valid Palindrome
Given a string, determine if it is a palindrome,
considering only alphanumeric characters and ignoring cases.
Example
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note
Have you consider that the string might be empty?
This is a good question to ask during an interview.
For the purpose of this problem,
we define empty string as valid palindrome.
Challenge
O(n) time without extra memory.
#signal to '';str.lower();reverse and compare
def palindrome(s):
signal=(',','.',':',';',' ','?')
for i in range(len(signal)):
s=s.replace(signal[i],"")
s=str.lower(s)
reverse=s[::-1]
return s==reverse
Notes:
1.Null signal is "",not '';
2.string is an important part in code; str.lower() s.replace() should be remembered.
class Solution:
# @param {string} s A string
# @return {boolean} Whether the string is a valid palindrome
def isPalindrome(self, s):
if not s:
return True
l, r = 0, len(s) - 1
while l < r:
# find left alphanumeric character
if not s[l].isalnum():
l += 1
continue
# find right alphanumeric character
if not s[r].isalnum():
r -= 1
continue
# case insensitive compare
if s[l].lower() == s[r].lower():
l += 1
r -= 1
else:
return False
#
return True
##functions learning:Python isalnum() 方法检测字符串是否由字母和数字组成。
两步走:
- 找到最左边和最右边的第一个合法字符(字母或者字符)
- 一致转换为小写进行比较
Longest Palindromic Substring
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.
Example
Given the string = "abcdzdcab", return "cdzdc".
Challenge
O(n2) time is acceptable. Can you do it in O(n) time.