How to Reverse Words in a String?

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

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) —

推荐阅读:
robots.txt的格式、写法及其对于WordPress的seo作用  无需修改代码 轻松隐藏WordPress管理工具栏  修改WordPress标签云字体大小及标签显示数量的方法  巧用wordpress更新服务 提升搜索引擎收录文章的速度  无需登陆FTP 新建一个wordpress主题文件  wordpress响应式杂志主题—Semicolon  禁止wordpress仪表盘加载谷歌字体链接  通过wordpress仪表盘修改wp_options数据表  荆州古城作文400字  过程胜过结局作文800字 
评论列表
添加评论