思路1:采用中间变量替换
思路2:采用异或的形式【注意:python中字符串不能直接异或,需要采用ord和chr来转化】
#反转字符串 def reverseStr(s): if not s: return s ch = list(s) i , j = 0 , len(s)-1 while i < j: ch[i] = chr(ord(ch[i]) ^ ord(ch[j])) ch[j] = chr(ord(ch[i]) ^ ord(ch[j])) ch[i] = chr(ord(ch[i]) ^ ord(ch[j])) # ch[i] = ch[i] ^ ch[j] 【错误的形式】 # ch[j] = ch[i] ^ ch[j] # ch[i] = ch[i] ^ ch[j] i += 1 j -= 1 return "".join(ch) s = ‘abcdef‘ print(reverseStr(s))
#反转字符串 def reverseStr(s): if not s: return s ch = list(s) i , j = 0 , len(s)-1 while i < j: ch[i] = chr(ord(ch[i]) ^ ord(ch[j])) ch[j] = chr(ord(ch[i]) ^ ord(ch[j])) ch[i] = chr(ord(ch[i]) ^ ord(ch[j])) i += 1 j -= 1 return "".join(ch) #s = ‘abcdef‘ #print(reverseStr(s)) #将句子反转,单词不反转。 def reverseWord(s): if not s: return s rs = reverseStr(s) arr = rs.split(‘ ‘) res = [] for a in arr: res.append(reverseStr(a)) return ‘ ‘.join(res) s = ‘I love dogs‘ print(reverseWord(s))
代码2:
def rotateWord(words): if words == None or len(words) == 0: return words = list(words[::-1]) l , r = -1 , -1 for i in range(len(words)): if words[i] != ‘ ‘: l = i if (i == 0 or words[i-1] ==‘ ‘) else l r = i if (i == len(words)-1 or words[i+1] == ‘ ‘) else r if l != -1 and r != -1: # reverse(words,l,r) words[l:r+1] = words[l:r+1][::-1] l , r = -1 , -1 return ‘‘.join(words) # def reverse(words,l,r): # tmp = ‘‘ # while l<r: # tmp = words[l] # words[l] = words[r] # words[r] = tmp # l += 1 # r -= 1 words = ‘dogs love pigs‘ rotateWord(words)
代码:
##将字符串的size大小的左半区移到右边,如size=3,“ABCDE”变成“DEABC” ###三步反转法 def reverseStr(s): if not s: return s ch = list(s) i , j = 0, len(s)-1 while i < j: ch[i] = chr(ord(ch[i])^ord(ch[j])) ch[j] = chr(ord(ch[i])^ord(ch[j])) ch[i] = chr(ord(ch[i])^ord(ch[j])) i += 1 j -= 1 return "".join(ch) def reroteStr(s,size): if not s: return s if size > len(s): return s s = reverseStr(s) n = len(s) - size left = reverseStr(s[:n]) right = reverseStr(s[size-1:]) return left + right s = ‘ABCDE‘ size = 3 print(reroteStr(s,size))
思路:首尾指针查找大小写字母,替换
代码:
def sortStr(ss): if len(ss)<=1: return ss s = list(ss) i = 0 j = len(s)-1 while i != j: if s[j].islower(): s[i] , s[j] = s[j] , s[i] i += 1 elif s[j].isupper(): j -= 1 return ‘‘.join(s) s = ‘aHjDFksn‘ print(sortStr(s))
原文:https://www.cnblogs.com/Lee-yl/p/10463243.html