【LeetCode】面试题05. 替换空格

题目:

思路:

通过Python有很多方便简单的解法,但本题考察的是字符串操作,用C++更好一些(利用String可遍历的性质)

代码:

Python

class Solution(object):
    def replaceSpace(self, s):
        """
        :type s: str
        :rtype: str
        """
        # return s.replace(' ', '%20')
        # return ''.join(('%20' if c==' ' else c for c in s))
        return '%20'.join(s.split(' '))

C++

class Solution {
public:
    string replaceSpace(string s) {
        string result;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == ' ') {
                result += "%20";
            }
            else {
                result += s[i];
            }
        }
        return result;
    }
};

猜你喜欢

转载自www.cnblogs.com/cling-cling/p/12894126.html