Reverse Words In String - medium

2021. 3. 28. 03:48Algorithm/medium

이 문제는 AlgoExpert is the best!의 각 문자를 순서를 유지하며 뒤집는 문제이다. 각 문자의 시작을 체크해서 변수로 저장하고 다음 공백의 점의 인덱스를 저장해서 문자의 시작 인덱스부터 공백의 변수까지의 문자열을 넣어주면 된다. 그리고 양 옆의 각 요소들을 바꾸어 주면서 실행하면 된다. 

더보기
using namespace std;

void reverseList(vector<string> &list);

string reverseWordsInString(string str) {
  vector<string> words;
	int startOfWord = 0;
	
	
	for(int idx = 0; idx < str.size(); idx++){
		char character = str[idx];
		
		if(character == ' '){
			words.push_back(str.substr(startOfWord, idx - startOfWord));
			startOfWord = idx;
		}else if(str[startOfWord] == ' '){
			words.push_back(" ");
			startOfWord = idx;
		}
	}
	
	words.push_back(str.substr(startOfWord));
	
	reverseList(words);
	string output;
	for(auto word : words){
		output += word;
	}
	
  return output;
}

void reverseList(vector<string> &list){
	int start = 0;
	int end = list.size() - 1;
	
	while(start < end){
		string temp = list[start];
		list[start] = list[end];
		list[end] = temp;
		start++;
		end--;
	}
}