This is an interview question:
Delete the blank characters at the beginning and end of the string, and convert (merge) Multiple spaces in the middle of the array into one. For example! "Changed to" I like python! ".
The problem is clear. The key is to reduce the number of characters to move. To reduce the number of characters to be moved, you can just move the characters to an accurate position at a time. Do not move unnecessary characters. The following provides some simple Python code.
#!/usr/bin/pythonimport sysdef rmblank(blankstr): new_start=0 i=0 blankspace=False while i<len(blankstr): #move behind chars to new start point if blankstr[i]!=' ': blankstr[new_start]=blankstr[i] new_start+=1 blankspace=True else: #if more than one blank, move behind chars to new start point if blankspace==True: blankstr[new_start]=blankstr[i] new_start+=1 blankspace=False i+=1 return blankstr[0:new_start]def main(): blankstr=" I like python ! " print blankstr print ''.join(rmblank(list(blankstr)))if __name__=='__main__': main()
References:
Jude Zou's http://www.oschina.net/code/snippet_142087_4696