이 문제에서는 문자열 str이 제공됩니다. 우리의 임무는 C++의 문자열에서 가장 작은 단어와 가장 큰 단어를 찾는 프로그램을 만드는 것입니다.
문제 설명 − 여기에 문자열의 모든 단어 중에서 길이가 최대 및 최소인 단어를 찾아야 하는 문자열이 있습니다. 공백 문자나 null(\0) 문자를 사용하여 단어를 구분합니다.
문제를 이해하기 위해 예를 들어보겠습니다.
입력
str = “Learn Programming at TutorialsPoint”
출력
smallest word = at largest word = Tutorialspoint
솔루션 접근 방식
가장 작은 단어와 가장 큰 단어를 찾기 위해 ' '(공백 문자) 또는 '\0' 문자를 사용하여 표시되는 단어의 시작과 끝을 위한 두 개의 인덱스를 사용하여 각 단어의 길이를 찾습니다. 그런 다음 시작 및 끝 인덱스를 사용하여 maxLength와 minlength를 찾습니다. 그리고 현재 단어의 길이를 기반으로 가장 작은 단어와 가장 큰 단어를 업데이트합니다.
우리 솔루션의 작동을 설명하는 프로그램
예시
#include<iostream>
#include<cstring>
using namespace std;
void minMaxLengthWords(string str){
int StrLength = str.length();
int startIndex = 0, endIndex = 0;
int minLength = StrLength, maxLength = 0, currentLength;
string smallest, largest;
while (endIndex <= StrLength){
if (str[endIndex] != '\0' && str[endIndex] != ' ')
endIndex++;
else{
currentLength = endIndex - startIndex;
if (currentLength < minLength){
smallest = str.substr(startIndex, currentLength);
minLength = currentLength;
}
if (currentLength > maxLength){
largest = str.substr(startIndex, currentLength);
maxLength = currentLength;
}
endIndex++;
startIndex = endIndex;
}
}
cout<<"Smallest Word from the string is "<<smallest<<"\n";
cout<<"Smallest Word from the string is "<<largest;
}
int main() {
string a = "Learn Programming at TutorialsPoint";
minMaxLengthWords(a);
} 출력
Smallest Word from the string is at Smallest Word from the string is TutorialsPoint