首页 > 其他 > 详细

1.4 Write a method to replace all spaces in a string with'%20'.

时间:2015-09-16 21:43:25      阅读:192      评论:0      收藏:0      [点我收藏+]

这题另外要求:如果用 Java 的话,要用字符数组。

【初步思路】:

新建一个字符数组,大小为原字符串的三倍, 然后遍历原字符串,将相应元素置入数组(如果是空格则用%20代替)

暂时没想到 in-place 的方法。

【时间复杂度】:O(n)

【空间复杂度】:O(n)

public char[] solu(char[] s) {
        char[] result = new char[s.length * 3];
        for (int i = 0, j = 0; i < s.length; i++) {
            int ascii = s[i];
            if (ascii == 32 ) {
                result[j++] = ‘%‘;
                result[j++] = ‘2‘;
                result[j++] = ‘0‘;
            } else {
                result[j] = s[i];
                j++;
            }
        }
        return result;
    }

 

 

2015-09-16

1.4 Write a method to replace all spaces in a string with'%20'.

原文:http://www.cnblogs.com/whuyt/p/4814524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!