码迷,mamicode.com
首页 > 其他好文 > 详细

Space Replacement

时间:2016-07-10 13:56:16      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.

You code should also return the new length of the string after replacement.

 Notice

If you are using Java or Python,please use characters array instead of string.

Example

Given "Mr John Smith", length = 13.

The string after replacement should be "Mr%20John%20Smith", you need to change the string in-place and return the new length 17.

分析:

先过一遍,找出string里的空格个数,这样就可以确定新string的总长度,我们可以从length -1 那个地方倒着插入字符。

 1 public class Solution {
 2     /**
 3      * @param string: An array of Char
 4      * @param length: The true length of the string
 5      * @return: The true length of new string
 6      */
 7     public int replaceBlank(char[] str, int length) {
 8         if (str == null || str.length == 0) return 0;
 9         
10         int count = 0;
11         for (int i = 0; i < str.length; i++) {
12             if (str[i] ==  ) count++;
13         }
14         
15         int index = length + 2 * count - 1;
16 
17         for (int i = length -1; i >= 0; i--) {
18             if (str[i] ==  ) {
19                 str[index--] = 0;
20                 str[index--] = 2;
21                 str[index--] = %;
22             } else {
23                 str[index--] = str[i];
24             }
25         }
26         
27         
28         return length + 2 * count;
29         
30     }
31 }

 

Space Replacement

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5657474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!