【LeetCode】Reverse Words in a String
2014-03-16 10:51
561 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
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.
Solution:
1. Python
2. C++
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
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.
Solution:
1. Python
print(' '.join(input().split()[::-1]));
2. C++
int main(int argc, const char * argv[]) { // insert code here... string myText; cout << "enter a sentence:" << endl; getline(cin, myText); istringstream iss(myText); myText = ""; string token; while(getline(iss, token, ' ')) { if (token.empty()) { continue; } myText = token + (myText.empty()? "":" ") + myText; } cout << myText << endl; }
相关文章推荐
- 【Leetcode】Reverse Words in a String JAVA
- [LeetCode]Reverse Words in a String-反转单词
- LeetCode---Reverse Words in a String
- [LeetCode186]Reverse Words in a String II
- leetcode151: Reverse Words in a String
- LeetCode-Reverse Words in a String II
- [LeetCode]Reverse Words in a String
- Leetcode 151 Reverse Words in a String
- Leetcode-Reverse words in string
- 【leetcode题解】1 - Reverse Words in a String
- Leetcode - Python - Reverse Words in a String
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- [LeetCode] Reverse Words in a String
- Leetcode之Reverse Words in a String
- [LeetCode]题解(python):151-Reverse Words in a String
- leetcode:Reverse Words in a String【Python版】
- leetcode 151 —— Reverse Words in a String
- leetcode 虐我篇之(一)Reverse Words in a String
- 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】
- leetcode--Reverse Words in a String