力扣题:字符串的反转-11.23

力扣题-11.23

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:557. 反转字符串中的单词 III

解题思想:先读取单词,然后将单词进行翻转即可
力扣题:字符串的反转-11.23_第1张图片

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        word_list = s.split()
        string = ''
        for i in range(len(word_list)):
            string += self.reverse(word_list[i]) + ' '
        return string.rstrip()

    def reverse(self, s):
        s_list = list(s)
        for i in range(len(s_list)//2):
            temp = s_list[i]
            s_list[i] = s_list[len(s_list)-i-1]
            s_list[len(s_list)-i-1] = temp
        return ''.join(s_list)
class Solution {
public:
        string reverseWords(string s) {
        string result = "";
        int start = 0;
        int temp = 0;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] != ' ') {
                temp += 1;
            } else {
                result += reverse(s.substr(start, temp)) + ' ';
                start = i + 1;
                temp = 0;
            }
        }
        result += reverse(s.substr(start, temp)); 
        return result;
    }

    string reverse(const string &s) {
        string reversed = s;
        for (int i = 0; i < reversed.size() / 2; i++) {
            char temp = reversed[i];
            reversed[i] = reversed[reversed.size() - 1 - i];
            reversed[reversed.size() - 1 - i] = temp;
        }
        return reversed;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)