이 문제에서는 두 개의 문자열 str과 conStr이 주어집니다. 우리의 과제는 주어진 문자열 str이 conStr로 시작하고 끝나는지 확인하는 것입니다.
문제 이해를 위한 예시
입력: str = "abcprogrammingabc", conStr = "abc"
출력: True
위 예시에서 문자열 str은 "abc"로 시작하고 "abc"로 끝나기 때문에 결과는 True입니다.
해결 접근 방법
이 문제를 해결하려면 문자열 str이 conStr로 시작하는지(접두사) 그리고 conStr로 끝나는지(접미사)를 모두 검사해야 합니다. 구체적인 단계는 다음과 같습니다.
알고리즘 단계
1. str의 길이(size)와 conStr의 길이(consSize)를 구합니다.
2. size가 consSize보다 작으면 str이 conStr을 포함할 수 없으므로 false를 반환합니다.
3. str의 앞부분에서 consSize만큼 잘라낸 부분 문자열(접두사)이 conStr과 일치하는지 확인합니다.
4. str의 뒷부분에서 consSize만큼 잘라낸 부분 문자열(접미사)이 conStr과 일치하는지 확인합니다.
5. 두 조건이 모두 참이면 true, 하나라도 거짓이면 false를 반환합니다.
C++에서는 substr() 함수로 부분 문자열을 추출하고, compare() 함수로 두 문자열을 비교할 수 있습니다.
솔루션 구현 예제 코드
#include <bits/stdc++.h>
using namespace std;
bool isPrefSuffPresent(string str, string conStr) {
int size = str.length();
int consSize = conStr.length();
if (size < consSize)
return false;
return (str.substr(0, consSize).compare(conStr) == 0 && str.substr(size-consSize, consSize).compare(conStr) == 0);
}
int main() {
string str = "abcProgrammingabc";
string conStr = "abc";
if (isPrefSuffPresent(str, conStr))
cout<<"The string starts and ends with another string";
else
cout<<"The string does not starts and ends with another string";
return 0;
}출력 결과
The string starts and ends with another string
코드 설명
isPrefSuffPresent() 함수는 먼저 str의 길이가 conStr의 길이보다 짧은 경우 false를 반환하여 유효성을 검사합니다. 이후 substr(0, consSize)로 문자열의 처음부터 conStr 길이만큼 추출한 접두사와, substr(size-consSize, consSize)로 문자열 끝에서 conStr 길이만큼 추출한 접미사를 각각 compare() 함수로 conStr과 비교합니다. 두 비교 결과가 모두 0(일치)이면 true를 반환합니다.
예제에서 str = "abcProgrammingabc"는 "abc"로 시작하고 "abc"로 끝나므로 프로그램은 해당 문자열이 다른 문자열로 시작하고 끝난다는 메시지를 출력합니다.