首页 > 其他 > 详细

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

时间:2020-05-15 15:45:03      阅读:35      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

思路:

通过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;
    }
};

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

原文:https://www.cnblogs.com/cling-cling/p/12894126.html

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