-
[LeetCode] 151. Reverse Words in a StringLeetCode 2021. 10. 20. 13:31728x90
https://leetcode.com/problems/reverse-words-in-a-string/
Reverse Words in a String - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Reverse Words in a String


String이 주어졌을때, 공백으로 이를 분절해서 역으로 재배치하는 문제다.
공백이 여러개 있을 경우엔 하나만 출력하고, 맨 앞과 맨 뒤의 공백은 제거(trim)한다.
풀이는 아래와 같다.
가장 먼저 String을 역으로 출력하는걸 생각해 볼 수 있는데, 그럴 경우 공백으로 구분된 단어내의 알파벳마저 역으로 출력되어 버린다.
따라서 String을 역으로 훑되, 새로운 String을 만들때는 기존 string의 앞에 글자를 하나씩 붙여주자.
그러다가 공백이 생길 경우엔, 이 공백+string을 따로 저장해두고, 새로 string을 만들어 반복해주자.
마지막으로, 제일 앞에 공백이 있을테니 앞의 공백만 제거해 출력해주면 된다.
전체 풀이 코드
class Solution { public: string reverseWords(string s) { string ret = ""; string temp = ""; for (int i=s.size()-1; i>-1; i--) { if (s[i]!=' ') temp=s[i]+temp; else if (temp.size() && temp[temp.size()-1]!=' ' && i) { ret+=' ' + temp; temp = ""; } } if (temp.size()) ret+=' ' + temp; return ret.substr(1); } };'LeetCode' 카테고리의 다른 글
[LeetCode] 1466. Reorder Routes to Make All Paths Lead to the City Zero (0) 2021.10.20 [LeetCode] 743. Network Delay Time (0) 2021.10.20 [LeetCode] 538. Convert BST to Greater Tree (0) 2021.10.19 [LeetCode] 402. Remove K Digits (0) 2021.10.19 [LeetCode] 496. Next Greater Element I (0) 2021.10.19