[LeetCode] 151. Reverse Words in a String 翻转字符串中的单词

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

Clarification:

  • What constitutes a word?
  • A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
  • Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
  • Reduce them to a single space in the reversed string.

把一个字符串中的单词逆序,单词字符顺序不变。

解法1: New array, 新建一个数组,把字符串以空格拆分成单词存到数组,在把单词逆序拷贝进新数组。

解法2: One place,不能新建数组,在原数组的基础上换位。把字符串的所以字符逆序,然后在把每个单词的字符逆序。

Java: New array, two pass

public String reverseWords(String s) {
    String[] words = s.trim().split("\\s+");
    if(words.length == 0) {
        return "";
    }
    StringBuilder sb = new StringBuilder(words[words.length-1]);
    for(int i=words.length-2; i >=0; i--) {
        sb.append(" "+words[i]);
    }
    return sb.toString();
}

Java: New array, one pass

public String reverseWords(String s) {
    StringBuilder sb = new StringBuilder();
    int end = s.length();
    int i = end-1;
    while(i>=0) {
        if(s.charAt(i) == ‘ ‘) {
            if(i < end-1) {
                sb.append(s.substring(i+1, end)).append(" ");
            }
            end = i;
        }
        i--;
    }
    sb.append(s.substring(i+1, end));
    return sb.toString().trim();
}

Java: New array, one pass

public String reverseWords(String s) {
    StringBuilder sb = new StringBuilder();
    int last = s.length();
    for(int i=s.length()-1; i>=-1; i--) {
        if(i==-1 || s.charAt(i)==‘ ‘) {
            String word = s.substring(i+1, last);
            if(!word.isEmpty()) {
                if(sb.length() != 0) sb.append(‘ ‘);
                sb.append(word);
            }
            last = i;
        }
    }
    return sb.toString();
}

Java:One place

public String reverseWords(String s) {
    if(s == null || s.isEmpty()) return s;
    char[] data = s.toChartArray();
    int n = data.length;
    reverse(data, 0, n-1);  

    int last = -1;
    for(int i=0; i<=n; i++) {
        if(i == n || data[i] == ‘ ‘) {
            if(i-last>1) reverse(data, last+1, i-1);
            last = i;
        }
    }  

    return new String(data);
}  

private void reverse(char[] data, int start, int end) {
    while(start < end) {
        char tmp = data[start];
        data[start++] = data[end];
        data[end--] = tmp;
    }
}

Python: New array

class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        return ‘ ‘.join(reversed(s.split()))

C++:

class Solution {
public:
    void reverseWords(string &s) {
        int storeIndex = 0, n = s.size();
        reverse(s.begin(), s.end());
        for (int i = 0; i < n; ++i) {
            if (s[i] != ‘ ‘) {
                if (storeIndex != 0) s[storeIndex++] = ‘ ‘;
                int j = i;
                while (j < n && s[j] != ‘ ‘) s[storeIndex++] = s[j++];
                reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
                i = j;
            }
        }
        s.resize(storeIndex);
    }
};

类似题目:

[LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词 II

[LeetCode] 557. Reverse Words in a String III 翻转字符串中的单词 III  

  

  

  

  

原文地址:https://www.cnblogs.com/lightwindy/p/8537259.html

时间: 2024-10-13 18:59:10

[LeetCode] 151. Reverse Words in a String 翻转字符串中的单词的相关文章

151 Reverse Words in a String 翻转字符串里的单词

给定一个字符串,翻转字符串中的每个单词.例如,给定 s = "the sky is blue",返回 "blue is sky the".对于C程序员:请尝试用O(1) 时间复杂度的原地解法.说明:    什么构成一个词?    一系列非空格字符组成一个词.    输入字符串是否可以包含前导或尾随空格?    是.但是,您的反转字符串不应包含前导或尾随空格.    两个单词之间多空格怎么样?    将它们缩小到反转字符串中的单个空格.详见:https://leetc

[LeetCode] Reverse Words in a String 翻转字符串中的单词

Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) space. click to show clarification. Cl

[LeetCode] Reverse Vowels of a String 翻转字符串中的元音字母

Write a function that takes a string as input and reverse only the vowels of a string. Example 1:Given s = "hello", return "holle". Example 2:Given s = "leetcode", return "leotcede". 这道题让我们翻转字符串中的元音字母,元音字母有五个a,e,i,o

leetcode——Reverse Words in a String 旋转字符串中单词顺序(AC)

题目如下: Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". click to show clarification. Clarification: What constitutes a word? A sequence of non-space characters c

[LeetCode]151.Reverse Words in a String

题目 Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) space. click to show clarification.

leetCode 151. Reverse Words in a String 字符串反转 | Medium

151. Reverse Words in a String Given an input string, reverse the string word by word. For example,Given s = "the sky is blue",return "blue is sky the". 题目大意: 输入一个字符串,将单词序列反转. 思路1: 采用一个vector,来存放中间结果 将vector的结果倒序放入原字符串中. 思路2: 在字符串分割的时候

lintcode 容易题:Reverse Words in a String 翻转字符串

题目: 翻转字符串 给定一个字符串,逐个翻转字符串中的每个单词. 样例 给出s = "the sky is blue",返回"blue is sky the" 说明 单词的构成:无空格字母构成一个单词 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个 解题: 这个题目方法很多的 1.整体反转,对每个单词再反转,但是中间的多个空格还有单独处理 2.把后面的单词,拿到前面去.参考程序

Reverse Words in a String(翻转字符串)

给定一个字符串,逐个翻转字符串中的每个单词. Given s = "the sky is blue",return "blue is sky the". 单词的构成:无空格字母构成一个单词 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个 思路: 1.定义一个新的字符串str 接收原字符串删除首尾空字符后的字符串 trim(): 2.定义字符串tmp 存储遍历字符串时的每个单词:

[Swift]LeetCode186. Reverse Words in a String II $ 翻转字符串中的单词 II

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.The input string does not contain leading or trailing spaces and the words are always separated by a single space.For example,Given s = "t