LeetCode 557. Reverse Words in a String III
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
my answer:
class Solution(object):
def reverseWords(self, s):
new=s.split()
l=""
leng=len(new)
for i in range(leng):
length=len(new[i])
n=reversed(new[i])
for j in range(length):
l+=n.next()
l+=' '
return l.strip()
Time Limit Exceeded 哭
查了一下别人的做法
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(w[::-1] for w in s.split())
……路漫漫其修远兮
541. Reverse String II
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:
Input: s = “abcdefg”, k = 2
Output: “bacdfeg”
my answer:
class Solution(object):
def reverseStr(self, s, k):
new=""
i=0
length=len(s)
while (i*k)<length:
if length-i*k<k:
new+=s[i*k:][::-1]
elif length-i*k>=k and length-i*k<2*k:
new += s[i*k:(i+1)*k][::-1]
new += s[(i+1)*k:]
else:
new+=s[i*k:(i+1)*k][::-1]
new+=s[(i+1)*k:(i+2)*k]
i+=2
return new
本以为会超时的
看了下别人的答案
class Solution(object):
def reverseStr(self, s, k):
l=list(s)
for i in xrange(0,len(l),2*k):
l[i:i+k]=reversed(l[i:i+k])
return ''.join(l)
::>_<::