• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

9996번 런타임에러

24.06.28 16:03 작성 24.06.28 16:04 수정 조회수 50

0

#include <bits/stdc++.h>

using namespace std;

vector<string> split(string input,string delimiter){
	
	vector<string> ret;
	int delimiterPosition;
	while((delimiterPosition=input.find(delimiter))!=string::npos){
		ret.push_back(input.substr(0,delimiterPosition));
		input.erase(0,delimiterPosition+delimiter.length());
	}
	ret.push_back(input);
	
	return ret;
}

int main(){
	
	int N;
	cin>>N;
	fflush(stdin);
		
	string pattern;
	getline(cin,pattern);
	vector<string> splited_strings=split(pattern,"*");
	string first=splited_strings[0],last=splited_strings[1];
	
	string input[N];
	for(int i=0;i<N;i++) cin>>input[i];
	
	for(int i=0;i<N;i++){
		// 접두사 
		if(first!=input[i].substr(0,first.size())) { // 없으면 
			cout<<"NE\n";
			continue;
		}
		else input[i].erase(0,first.size()); // 있으면 
		
		// 접미사
		if(input[i].find(last)==string::npos) { // 없으면 
			cout<<"NE\n";
			continue;
		}
		else{ // 있으면
			 if(last==input[i].substr(input[i].size()-last.size())) cout<<"DA\n";
			 else cout<<"NE\n";
		}
	}
	
	return 0;
}

어디서 런타임에러를 유발하는 지 모르겠습니다.

답변 1

답변을 작성해보세요.

0

안녕하세요 상준님ㅎㅎ

먼저 getline을 쓸때는 주의사항이 있습니다.

image

해당부분 적용 + size부분 체킹 부분을 넣어서 다듬어봤습니다.

참고부탁드립니다.

#include <bits/stdc++.h>
using namespace std;

vector<string> split(const string& input, const string& delimiter) {
    vector<string> ret;
    size_t start = 0, end;
    while ((end = input.find(delimiter, start)) != string::npos) {
        ret.push_back(input.substr(start, end - start));
        start = end + delimiter.length();
    }
    ret.push_back(input.substr(start));
    return ret;
}

int main() {
    int N;
    cin >> N;
    string bufferflush;
    getline(cin, bufferflush); 
    string pattern;
    getline(cin, pattern); 
    vector<string> splited_strings = split(pattern, "*");
    string first = splited_strings[0], last = splited_strings[1];
    
    vector<string> input(N);
    for (int i = 0; i < N; ++i) {
        cin >> input[i];
    }
    
    for (int i = 0; i < N; ++i) {
        string current = input[i]; 
        if (current.size() < first.size() + last.size()) {
            cout << "NE\n";
            continue;
        } 
        if (current.substr(0, first.size()) != first) {
            cout << "NE\n";
            continue;
        }
         
        if (current.substr(current.size() - last.size()) != last) {
            cout << "NE\n";
            continue;
        } 
        cout << "DA\n";
    }
    
    return 0;
}


또 질문 있으시면 언제든지 질문 부탁드립니다.

좋은 수강평과 별점 5점은 제게 큰 힘이 됩니다. :)

감사합니다.

강사 큰돌 올림.


문상준님의 프로필

문상준

질문자

2024.07.03

재질문이 있습니다.

(제 코드에서) 우선 N을 입력받고, fflush로 입력 버퍼를 비웠고, pattern을 입력 받은 뒤에는 버퍼에 시작에 개행이 존재하지 않기 때문에, 입력 버퍼를 비우지 않아서 생기는 문제는 없어 보이는데, 어디서 잘못 이해하고 있는지 모르겠습니다.

image.png

또한, size 부분도

접두사가 없다면, NE 하고 continue

접두사가 있고, 접미사가 없으면, NE하고 continue

접두사가 있고, 접미사가 있어도, size() 조건은 만족 하지 못하면, NE하고 있기에 문제가 없어보입니다.

채널톡 아이콘