【華爲機試】句子逆序

題目描述

將一個英文語句以單詞爲單位逆序排放。例如“I am a boy”,逆序排放後爲“boy a am I”
所有單詞之間用一個空格隔開,語句中除了英文字母外,不再包含其他字符

輸入描述:將一個英文語句以單詞爲單位逆序排放。

輸出描述:得到逆序的句子

輸入  I am a boy

輸出  boy a am I

方法一分析:先把整個字符串反過來,在把每個單詞反過來。

#include <iostream>
#include <string>
using namespace std;

void reserve(string &s,int start,int end){
	int l = start, r = end;
	while (l < r)
		swap(s[l++], s[r--]);
}

int main(){
	string s;
	while (getline(cin, s)){
		if (s.empty()) continue;
		reserve(s,0,s.size()-1);
		int start = 0, end = 0;
		while (start<=end){
			while (s[end] != ' '){
				end++;
				if (s[end] == '\0') break;
			}
			reserve(s, start, end - 1);
			if (s[end] == '\0') break;
			start = ++end;
		}
		cout << s << endl;
	}
	return 0;
}

方法二分析:遍歷字符串,以單詞和空格爲單元,插入到結果字符串的前面;

#include <iostream>
#include <string>
using namespace std;

int main(){
	string s;
	while (getline(cin, s)){
		int i = 0;
		string res;
		while (i < s.size()){
			if (s[i] == ' ') 
				res.insert(res.begin(),s[i++]);
			else {
				string temp;  //temp用來保存單詞;
				while (i<s.size()&&s[i] != ' ')  //注意有個i<s.size(),否則i會越界;
					temp += s[i++];
				res = temp + res;
			}
		}
		cout << res << endl;
	}
	return 0;
}
發佈了63 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章