Delete the blank characters at the beginning and end of the string, and convert (merge) Multiple spaces (if any) in the middle of the array into one.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.