【剑指offer】面试题42:单词翻转顺序&左右旋转字符串

这里尽可能的不去用语言本身提供的函数。

将string逆置

def reverse(string):
	#return string[::-1]
	reversedStr = ''
	for i in xrange(len(string) - 1, -1, -1):
		reversedStr += string[i]
	return reversedStr
单词的翻转
def reverseWords(string):
	if len( string ) <= 1: return
	split = ' '
	reversedStr = ''
	word = ''
	# reverse every word in string
	for c in string:
		if c == split:
			word = reverse(word) + split
			reversedStr += word
			word = ''
		else:
			word += c
	# the last word
	reversedStr += reverse(word)
	# reverse the whole string
	reversedStr = reverse(reversedStr)
	return reversedStr

这里没有考虑前导空格之类的复杂情况,默认string是很规整的,单词间由一个空格隔开。

字符串的左右旋转。右旋转我们将字符串后面的n个字符移到最前面。通过參数direction来差别,实參为‘l',’L‘, ’r‘, ’R'.

'''
	@ if direction = 'l' or 'L', move n items from front to end
	@ if direction = 'r' or 'R', move n items from back to front
'''
def RotateString(string, n, direction):
	if n >= len(string) or n <= 0: 
		return string
	reversedStr = ''
	leftpart = ''
	rightpart = ''

	# move last n chiracter to front
	if direction == 'r' or direction == 'R': 
		n = len(string) - n
		
	for i in range(n):
		leftpart += string[i]

	for i in range(n, len(string)):
		rightpart += string[i]

	reversedStr += reverse(leftpart)
	reversedStr += reverse(rightpart)
	reversedStr = reverse(reversedStr)
	return reversedStr

若认为单词翻转的实现繁琐。也能够直接用语言本身提供的函数。可是不推荐。

def reverseWords(string):
	return ' '.join(string.split()[::-1])



【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10659066.html