📄 문제
문자열 myString이 주어집니다. myString을 문자 "x"를 기준으로 나눴을 때 나눠진 문자열 각각의 길이를 순서대로 저장한 배열을 return 하는 solution 함수를 완성해 주세요.
❗️ 제한사항
- 1 ≤ myString의 길이 ≤ 100,000
- myString은 알파벳 소문자로 이루어진 문자열입니다.
↕️ 입출력
myString | result |
"oxooxoxxox" | [1, 2, 1, 0, 1, 0] |
"xabcxdefxghi" | [0, 3, 3, 3] |
📝 풀이
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
using namespace std;
vector<string> split(string input, char delimiter)
{
vector<string> result; // 결과를 리턴할 string 벡터
stringstream ss(input); // sstream
string token; // split된 문자열을 임시로 담을 토큰
// getline 함수로 받아온 후 벡터에 삽입
while(getline(ss, token, delimiter))
result.push_back(token);
return result;
};
vector<int> solution(string myString) {
vector<int> answer;
vector<string> splited = split(myString, 'x');
for(string s : splited)
answer.push_back(s.length());
if(myString[myString.length() - 1] == 'x')
answer.push_back(0);
return answer;
}
- split 함수를 구현하여 문제를 해결하였습니다.
- 구분자인 x가 문자열의 가장 마지막에 있다면, x 후에 0개의 문자열이 있다고 가정하여 문제를 해결합니다.
'algorithms (C++)' 카테고리의 다른 글
[C++][프로그래머스] 배열의 원소 삭제하기 (0) | 2023.10.22 |
---|---|
[C++][프로그래머스] 전국 대회 선발 고사 (0) | 2023.10.22 |
[C++] 위상정렬(그래프 정렬) ⭐ (0) | 2023.10.20 |
[C++] 회장뽑기(플로이드 워샬) 🔥 (0) | 2023.10.20 |
[C++] 플로이드 워샬 알고리즘 ⭐ (0) | 2023.10.20 |