Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

思路:替换空格 #2

Open
YZcxy opened this issue Mar 26, 2019 · 0 comments
Open

思路:替换空格 #2

YZcxy opened this issue Mar 26, 2019 · 0 comments

Comments

@YZcxy
Copy link
Owner

YZcxy commented Mar 26, 2019

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

思路

本题可分为两种思路,一种没有多余的内存可用,一种使用多余的内存。
如果可以使用多余的内存,那么可以直接创建一个StringBuffer,用于拷贝String,每遇到一个空格,则在StringBuffer中添加%20。
如果不让使用多余的内存,那么最直接的方式就是每遍历到一个空格,就将字符串后面的字符都往后移两位,这样移动非常消耗时间。
所以我们可以采用优先遍历一次字符串,统计一共有多少个空格,那么最终的输出字符串的长度为原长度加上空格乘以二,然后我们从后往前遍历,将字符一个一个的拷贝到新长度的字符串的末尾。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant