How to Reverse Words in a String?

  • 时间:2020-10-06 11:32:45
  • 分类:网络文摘
  • 阅读:137 次

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Find Space and Reverse (C++)

We can walk through each character and find next space position or EOF. Then, we can reverse the substring and concatenate it to the result string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    string reverseWords(string s) {
        int len = s.length();
        int i = 0, j = 0;
        string r = "";
        while (i < len) {
            while ((i < len) && s[i] != ' ') ++ i;
            if ((i == len) || (s[i] == ' ')) {
                r += reverse(s.substr(j, i - j));    
            }
            if (i < len) r += ' ';
            j = ++ i;
        }
        return r;
    }
    
    string reverse(string s) {
        string r = s;
        for (int i = 0; i < r.length() / 2; ++ i) {
            char t = r[r.length() - 1 - i];
            r[r.length() - 1 - i] = r[i];
            r[i] = t;
        }
        return r;
    }
};
class Solution {
public:
    string reverseWords(string s) {
        int len = s.length();
        int i = 0, j = 0;
        string r = "";
        while (i < len) {
            while ((i < len) && s[i] != ' ') ++ i;
            if ((i == len) || (s[i] == ' ')) {
                r += reverse(s.substr(j, i - j));    
            }
            if (i < len) r += ' ';
            j = ++ i;
        }
        return r;
    }
    
    string reverse(string s) {
        string r = s;
        for (int i = 0; i < r.length() / 2; ++ i) {
            char t = r[r.length() - 1 - i];
            r[r.length() - 1 - i] = r[i];
            r[i] = t;
        }
        return r;
    }
};

The string reverse above implementation is O(N) time, and the reverse-words take O(N^2) considering the string concatenation in C++ is inefficient. Thus the overall complexity is O(N^3).

The C++ does not have a inbuilt split string method, however, you can use third party library such as boost.

The C++ std::reverse() takes two parameters: start and end iterator, then reverse it. So the above can be simplified without re-inventing the wheel:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
    string reverseWords(string s) {
        int i = 0, len = s.size();
        while (i < len) {
            int j = i;
            while ((j < len) && (s[j] != ' ')) j ++;
            std::reverse(begin(s) + i, begin(s) + j);
            i = j + 1;
        }
        return s;
    }
};
class Solution {
public:
    string reverseWords(string s) {
        int i = 0, len = s.size();
        while (i < len) {
            int j = i;
            while ((j < len) && (s[j] != ' ')) j ++;
            std::reverse(begin(s) + i, begin(s) + j);
            i = j + 1;
        }
        return s;
    }
};

Split and Reverse Algorithm in Java

In Java, we can split the string into an array of words, then we can concatenate the reversed substrings using String Builder, which is performant when the number of concatenation is big.

1
2
3
4
5
6
7
8
9
10
class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder r = new StringBuilder();
        for (String word: words) {
            r.append(new StringBuffer(word).reverse().toString() + " ");
        }
        return r.toString().trim();
    }
}
class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder r = new StringBuilder();
        for (String word: words) {
            r.append(new StringBuffer(word).reverse().toString() + " ");
        }
        return r.toString().trim();
    }
}

Reverse Words in a String using Python

With Python, we can reverse a string easily using [::-1] syntax sugar. Thus, it is trivial to solve this in Python:

1
2
3
4
5
6
class Solution:
    def reverseWords(self, s: str) -> str:
        ans = []
        for w in s.split(' '):
            ans.append(w[::-1])
        return ' '.join(ans)
class Solution:
    def reverseWords(self, s: str) -> str:
        ans = []
        for w in s.split(' '):
            ans.append(w[::-1])
        return ' '.join(ans)

Using C++ istringstream

We can use the C++ istringstream to parse each token/words – and reverse them on the fly.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
    string reverseWords(string s) {
        istringstream ss(s);
        string ans = "", str;
        while (ss >> str) {
            std::reverse(begin(str), end(str));
            ans += str + " ";
        }
        return ans.substr(0, ans.size() - 1);
    }
};
class Solution {
public:
    string reverseWords(string s) {
        istringstream ss(s);
        string ans = "", str;
        while (ss >> str) {
            std::reverse(begin(str), end(str));
            ans += str + " ";
        }
        return ans.substr(0, ans.size() - 1);
    }
};

Reversing string puzzles are often in interviews.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
Second Missing Pakastani Blogger Found Fleeing Country  Blogger Catches Several Runners Cheating In Philadelphia Maratho  Melania Trump Given The Green Light To Continue In Libel Suit Ag  How to Be a Better Financial Blogger  [2017] Review Of Kajabi: All-In-One Online Course & Membersh  7 Tips for SEO Rankings In 2017  Court Rules That Blogger Does Not Qualify For Unemployment Benef  How A Social Media Employee Advocacy Program Can Help Your Busin  5 Ways to Work on Your Blogging Strategy No Matter Where You Are  Everything You Need to Know About Web Hosting for Your Blog 
评论列表
添加评论