leetcode之Reverse Words in a String
2014-06-07 22:49
405 查看
原题如下:
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
这道题的题意很明确,首先想到的是将字符串按空格分割并存入字符串数组中,然后将分割后的字符串从后往前连接起来。这种思路是正确的,但可惜C++中没有实现字符串分割方法,所以需要自己实现split()方法,这里需要注意的是原字符串为空时直接返回,当原字符串都为空格时,需要将原字符串置空并返回。
补:Python代码实现如下:
Given an input string, reverse the string word by word.
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
这道题的题意很明确,首先想到的是将字符串按空格分割并存入字符串数组中,然后将分割后的字符串从后往前连接起来。这种思路是正确的,但可惜C++中没有实现字符串分割方法,所以需要自己实现split()方法,这里需要注意的是原字符串为空时直接返回,当原字符串都为空格时,需要将原字符串置空并返回。
class Solution { public: void reverseWords(string &s) { if(s.empty()) return; vector<string>v = split(s); s = ""; if(v.empty()) return; for(int i = v.size() - 1; i > 0; i--){ s.append(v[i]); s.append(1,' '); } s.append(v[0]); return; } vector<string>split(string s){ vector<string>v; string str; for(int i = 0; i < s.size(); i++){ if(s[i] == ' '){ if(!str.empty()){ v.push_back(str); str = ""; } } else str.append(1,s[i]); } if(!str.empty()) v.push_back(str); return v; }
补:Python代码实现如下:
class Solution: # @param s, a string # @return a string def reverseWords(self, s): L= s.strip().split() L.reverse() return ' '.join(L)其中,trip()方法去除字符串的首尾的空格,split将字符串按照空格分隔,当字符串为空且分隔方法split()的参数为空时,返回空列表。从这道题可以看出Python真的很强大!
相关文章推荐
- Leetcode 第151题 最新题解 Reverse Words in a String
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- LeetCode(151)Reverse Words in a String
- Leetcode: Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode with Python】 Reverse Words in a String
- [LeetCode]Reverse Words in a String
- leetcode Reverse Words in a String
- [leetcode]Reverse Words in a String
- Leetcode_Reverse-Words-in-a-String
- LeetCode | Reverse Words in a String
- Reverse Words in a String (LeetCode)
- [Leetcode Solution] Reverse Words in a String
- LeetCode151:Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [leetCode]Reverse Words in a String
- leetcode - Reverse Words in a String
- [LeetCode] Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 【LeetCode】Reverse Words in a String