728x90
반응형
문제를 아주 쉽게 풀어보자. 아주 그냥 초심자의 사고회로로 풀어버렸다. 너무너무나 초급의 풀이방법인 것 같다.
#include <string>
#include <vector>
using namespace std;
string solution(string s) {
string answer = "";
int a = s.size() / 2;
if(s.size() % 2 == 0){
answer.push_back(s[a - 1]);
answer.push_back(s[a]);
}
else{
answer.push_back(s[a]);
}
return answer;
}
(다른 사람의 풀이 확인하기)
이것과 비슷한 풀이 방법.
나는 push_back 함수를 사용해 배열에 원소를 추가해줬지만
아예 answer의 인덱스 값에 직접 값을 넣어주는 방법도 있다.
#include <string>
#include <vector>
using namespace std;
string solution(string s) {
string answer = "";
if(s.size()%2) answer=s[s.size()/2];
else {answer = s[s.size()/2-1];
answer+= s[s.size()/2];
}
return answer;
}
풀이 중에 substr 함수가 있길래 이 함수에 대해 찾아보기로 했다.
C++ 레퍼런스 - string 의 substr 함수
모두의 코드 C++ 레퍼런스 - string 의 substr 함수 작성일 : 2020-07-17 이 글은 159948 번 읽혔습니다. 문자열의 일부를 리턴한다. 문자열의 pos 번째 문자 부터 count 길이 만큼의 문자열을 리턴한다. 만약
modoocode.com
이렇게 알아보고 다른 사람들의 풀이를 한번 확인해보자면..
#include <string>
#include <vector>
using namespace std;
string solution(string s) {
string answer = "";
int len = s.length();
if (len%2 == 0) {
answer = s.substr((len/2)-1, 2);
} else {
answer = s[len/2];
}
return answer;
}
생각보다 빨리 풀어내어 기뻤다 :)
728x90
반응형
'프로그래머스 C++ > Level.1' 카테고리의 다른 글
프로그래머스 Level.1 수박수박수박수박수박수? (0) | 2024.03.20 |
---|---|
프로그래머스 Level.1 내적 (0) | 2024.03.20 |
프로그래머스 Level.1 제일 작은 수 제거하기 (0) | 2023.12.25 |
프로그래머스 Level.1 없는 숫자 더하기 (1) | 2023.11.13 |
프로그래머스 Level.1 음양 더하기 (0) | 2023.11.12 |