
문자열을 받은 다음에
문자열의 뒤에서부터보고,
앞에꺼랑 같으면 하나 지우고, 앞에꺼랑 다르면 find함수로 문자열에 그 문자의 개수가 1초과인지
확인하면 되지 않을까?
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string word;
cin >> n;
for(int i=0; i<n; i++){
cin >> word;
for(int j = word.length(); j>0; j--) {
if (word[j]==word[j-1]) word.erase(word.begin()+j);
else if (word.find(word[j])>1) n--; break;
}
} cout << n;
}
1트
자꾸 4, abab, abb를 입력하면 for문이 멈추고 2가 출력되는 문제가 생김.
문제가 뭘까
n--를 하면서 n이 줄어드니까 4에서 --가 두번 돌고 n이 2가 되니까 for문에서 탈출이 되고 2가 출력되는 것같다.
그래서 이 부분을 수정해서
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string word;
cin >> n;
int answer = n;
// 정담은 우선 입력받은 문자열 개수인 n에서 시작
for(int i=0; i<n; i++){ //n개 만큼 문자열을 입력받아야되니까 반복 시작.
cin >> word;
for(int j = word.length(); j>0; j--) {
// 입력받은 문자열의 길이만큼, 문자열의 뒤에서부터 반복.
if(word.length()<=2) break;
else if (word[j]==word[j-1]) {word.erase(word.begin()+j); continue;}
// 문자열 맨 뒤부터, 내가 보고 있는 문자가 그 앞에꺼랑 똑같으면 내가 보고있는 문자 지우기
else if (word.find(word[j])>1) answer--; break;
/* 내가 보고 있는 문자가 그 앞이랑 같지 않을때 내가 보고 있는 문자를 문자열에서 찾음.
그래서 1개 이상이 발견되면 이건 연속되지 않으니까 그룹단어가 아님. 그래서 답에서 --
그리고 for문 탈출해서 다음 문자열을 확인하러 다음 문자열로 넘어가기//
}
} cout << answer;
}
요렇게 변경함.
이번엔 왜 또 답이 4로 나오냐.....
그래서 계속된 시도 끝에 나온 코드
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
int n, answer;
string word;
cin >> n;
answer = n;
for(int i=0; i<n; i++){
cin >> word;
string w = word;
if (word.length()>3){
for(int j=1; j<word.length(); j++){
if (word[j]==word[j-1]) word.erase(word.begin()+j);
else if((count(word.begin(), word.end(), word[j]))>1){answer--; break;}}
}
} cout << answer;
}
여기서는 또 글자를 지우고 그 다음으로 넘어가버리면
ㅁㅁㄹㄹ 인덱스 1번을 확인해서
여기서 ㅁ하나 지웠을 때 ㅁㄹㄹ로 바뀌고,
j++해서 하나 넘어가 인덱스 2번을 확인하면 3번째 글자를 보게 됨. ㄹ 하나가 누락되니까 j--를 해서 다시 1번을 확인하게 바꿔주기로함
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
int n, answer;
string word;
cin >> n;
answer = n;
for(int i=0; i<n; i++){
cin >> word;
string w = word;
if (word.length()>2){
for(int j=0; j<word.length(); j++){
if (word[j]==word[j+1]) {word.erase(word.begin()+j); j--;}
else if((count(word.begin(), word.end(), word[j]))>1){answer--; break;}}
}
} cout << answer;
}
성공!
'C++ 문제풀기 > 백준-프로그래머스' 카테고리의 다른 글
| 프로그래머스 | 택배상자꺼내기 (2) | 2025.06.19 |
|---|---|
| 프로그래머스 | 키패드 누르기 (0) | 2025.06.19 |
| 프로그래머스 | 나선형으로 배열하기 (0) | 2025.06.17 |
| 백준 | 2941. 크로아티아 알파벳 (0) | 2025.06.17 |
| 백준 | 2606. 바이러스 (DFS) (1) | 2025.06.15 |