LintCode – Space Replacement

题目:http://www.lintcode.com/en/problem/space-replacement/

思路:

  1. 计算空格
  2. 创建一个新的string,长度为原先长度+2*空格数
  3. 用新string从后面还是加入char,如果空格则替换成%20
    public int replaceBlank(char[] string, int length) {
        // write your code here
        int index =0;
        int space =0;
        for(int i=0;i<length;i++){
            if(string[i] == ' '){
                space ++;
            }
        }
        
        index = space + space + length;
        
        char[] newstring = new char[index];
        for(int i=length -1;i>=0;i--){
            if(string[i] == ' '){
                newstring[index-1] = '0';
                newstring[index-2] = '2';
                newstring[index-3] = '%';
                index = index -3;
            }
            else{
                newstring[index-1] = string[i];
                index --;
            }
        }
        int newlength = newstring.length;
        return newlength;
    }

本站原创文章皆遵循“署名—非商业性使用—相同方式共享 4.0 协议 (CC BY-NC-SA 4.0)”。共享、演绎请保留以下标注:

原文作者:Jake Tao,来源:「LintCode – Space Replacement」

120
0 0 120

延伸阅读

发表回复

登录后才能评论
分享本页
返回顶部