Reverse Words in a String III

原题: https://leetcode.com/problems/reverse-words-in-a-string-iii/description/

题意: 给定字符串,将每个单词逐字符逆置,返回新字符串。

约定:(1)字符串中单词之间有且只有1个空格分开。

例子: 

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
标签: iii、words、reverse、ekat、edocteel、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • SLPH
    2017-08-12 17:32:27 1楼#1层
    Python解法一:
    class Solution(object):
        def reverseWords(self, s):
            """
            :type s: str
            :rtype: str
            """
            return ' '.join(w[::-1] for w in s.split())
  • SLPH
    2017-08-12 17:32:52 2楼#1层
    Python解法二:
    class Solution(object):
        def reverseWords(self, s):
            """
            :type s: str
            :rtype: str
            """
            clist, size = list(s), len(s)
            p = q = 0
            while p < size:
                while q < size and s[q] != ' ': q += 1
                for x in range((q - p) / 2):
                    clist[p + x], clist[q - x - 1] = clist[q - x - 1], clist[p + x]
                p = q = q + 1
            return ''.join(clist)
  • SLPH
    2017-08-12 17:33:16 3楼#1层
    C++解法一:
    class Solution {
    public:
        string reverseWords(string s) {
            string res = "", t = "";
            istringstream is(s);
            while (is >> t) {
                reverse(t.begin(), t.end());
                res += t + " ";
            }
            res.pop_back();
            return res;
        }
    };
  • SLPH
    2017-08-12 17:33:30 4楼#1层
    C++解法二:
    class Solution {
    public:
        string reverseWords(string s) {
            int start = 0, end = 0, n = s.size();
            while (start < n && end < n) {
                while (end < n && s[end] != ' ') ++end;
                for (int i = start, j = end - 1; i < j; ++i, --j) {
                    swap(s[i], s[j]);
                }
                start = ++end;
            }
            return s;
        }
    };
  • 回复
隐藏