题目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
- 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.给你一个字符串,分割成单个单词后逆序输出,每个单词中间间隔一个空格。
注意:1.输出时结尾部分没有空格。
2.给定的字符串单词中间可能间隔不只是一个空格。
3.给定的字符串也许会自带前导和后导空格。
算法:
C++版本:
String 、STL 的 Vector
Java版本:
split 函数的学习和正则表达式
思路:
C++版本:
1.依次遍历给定的字符串的每一个字符,分割出单个的单词。
2.输出栈中的单词,重新拼成字符串就可以了。
Java版本:
1.用正则表达式和 split()函数分割给定的字符串为字符串数组。
2.逆序遍历字符串数组,拼接上非空单词即可。
3.将每一个单词存入栈 Vector<String> 。
code:
C++版本:
/**
author:free斩
0 minutes ago Accepted 20 ms cpp
*/
#include <iostream>
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
int len = s.size();
if(0 == len) {
s = "";
return;
}
stack<string> st;
while(!st.empty()) st.pop();
string ans;
for(int i = 0; i < len; i++) {
char c = s[i];
if(c != ' ') {
ans += s[i];
if(i == (len-1) || s[i+1] == ' ') {
if(ans.empty() == false) {
st.push(ans);
}
ans = "";
}
}
}
if(st.empty()) {
s = "";
return;
}
s = st.top(); st.pop();
while(st.empty() == false) {
s += " ";
s += st.top();
st.pop();
}
}
};
int main()
{
Solution ss;
string s = " Hello Word! ";
ss.reverseWords(s);
cout << s << endl;
return 0;
}
Java版本:
package ReverseWordsInaString;
/**
* Accepted 408 ms java
* @author freezhan
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = " I am ";
s = reverseWords(s);
System.out.println(s);
}
private static String reverseWords(String s) {
if(0 == s.length()) return "";
String[] strArry = s.split("\\s+");
int len = strArry.length;
if(len == 0) return "";
StringBuffer sb = new StringBuffer();
len -= 1;
int index = len;
for(int i = len; i >= 0; i++) {
if(!strArry[i].isEmpty()) {
sb.append(strArry[i]);
index = i;
break;
}
}
for(int i = index-1; i >= 0; i--) {
if(!strArry[i].isEmpty()) {
sb.append(" ").append(strArry[i]);
}
}
return sb.toString();
}
}
弱到不可以,边准备考研,边开始刷 leetcode 了 ...
前面看了下 python 传说中最好用的语言,没有之一,不过很多东西还是不了解。
虽然很弱,依旧觉得唯有 C 才能体现算法之美,不过语言终究不是问题。
先贴上 C++ 和 Java的代码 ,以后若有闲情再折腾 python 版本好了【基本说出这样的话的人就不会再写了吧,啊啊啊!依旧是如此的懒惰,怎么得了T_T】。