讨论/《图解算法数据结构》 - 剑指 Offer 05. 替换空格/
《图解算法数据结构》 - 剑指 Offer 05. 替换空格
共 41 个回复
class Solution {
public:
    string replaceSpace(string s) {
        string res;
        for(int i = 0; i < s.size(); ++i){
            if(s[i] != ' ')
                res += s[i];
            else{
                res += '%';
                res += '2';
                res += '0';
            }
        }
        return res;
    }
};
14

Solution With Python3:
return s.replace(' ','%20')

7
class Solution {
    
    private static final String REPLACE_SPACE_VALUE = "%20";
    
    public String replaceSpace(String s) {
        StringBuilder builder = new StringBuilder();
        char[] ch = s.toCharArray();
        for (char c : ch) {
            if (c == ' ') {
                builder.append(REPLACE_SPACE_VALUE);
            } else {
                builder.append(c);
            }
        }
        
        return builder.toString();
    }
    
}
7
class Solution {
public:
    string replaceSpace(string s) {
        string result;
        for(int i =0; i < s.length(); i++){
            if(s[i] == ' '){
                result += "%20";
            }else{
                result += s[i];
            }
        }
        return result;
    }
};
6

java

class Solution {
    public String replaceSpace(String s) {
        return ("".equals(s) || s==null)?"":s.replace(" ","%20");  
    }
}
2

class Solution {
public String replaceSpace(String s) {
return s.replace(" ","%20");
}
}

2

c++中,string是可变的哦

2

我这算是偷鸡吗?

2
class Solution {
public:
    string replaceSpace(string s) {
        int length=s.size();
        for(int i=0;i<length;i++)
        {
            if(s[i]==' ')
            {
                s.replace(i,1,"%20");
                length+=2;
            }
        }
        return s;
    }
};
2
class Solution {
    public String replaceSpace(String s) {
        StringBuilder sb = new StringBuilder();
        for(char c : s.toCharArray()){
            if(c != ' '){
                sb.append(c);
            } else {
                sb.append("%20");
            }
        }
        return sb.toString();
    }
}
2