这是一道面试题:
删除字符串开始及末尾的空白符,并且把数组中间的多个空格(如果有)符转化(合并)为1个。例如把“ I like python ! "变成”I like python !“。
问题很明确,关键是要减少字符的移动次数。要减少字符的移动次数,如果能一次性就把字符移到准确地位置就好了,不要做不必要的移动。下面给出用python些的简单代码。
#!/usr/bin/python
import sys
def 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()
参考文献:
Jude Zou的http://www.oschina.net/code/snippet_142087_4696