넘치게 채우기

[LeetCode] 151. Reverse Words in a String 본문

PS/LeetCode

[LeetCode] 151. Reverse Words in a String

riveroverflow 2023. 8. 3. 15:28
728x90
반응형

https://leetcode.com/problems/reverse-words-in-a-string/description/?envType=study-plan-v2&envId=top-interview-150 

 

Reverse Words in a String - LeetCode

Can you solve this real interview question? Reverse Words in a String - Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a strin

leetcode.com

문제 유형 : 문자열 처리

문제 난이도 : Medium

 

문제

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

 

문자열 s의 단어를 뒤집어서 출력하시오. 단어들은 최소 한 칸 이상의 공백으로 구분됩니다.

단어 사이에 여러 개의 공백이 있을 수 있습니다. 중복된 공백은 지우십시오.

 

풀이

stringsteam을 이용하여 공백으로 구분된 문자열을 단어로 받습니다.

스택에 순서대로 단어를 쌓아줍니다.

스택에서 순서대로 꺼내어서 단어를 나열해주면 됩니다.

 

코드(C++)

class Solution {
public:
    string reverseWords(string s) {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    stringstream ss(s);
    string word;
    stack<string> words;

    while (ss >> word) {
        words.push(word);
    }

    string result;
    while(!words.empty()){
        result += words.top();
        if(words.size() <= 1) break;
        result += " ";
        words.pop();
    }

    return result;
    }
};
728x90
반응형

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] 6. Zigzag Conversion  (0) 2023.08.05
[LeetCode] 139. Word Break  (0) 2023.08.04
[LeetCode] 14. Longest Common Prefix  (0) 2023.08.02
[LeetCode] 12. Integer to Roman  (0) 2023.08.01
[LeetCode] 42. Trapping Rain Water  (0) 2023.07.31