Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

문자열을 확인하는 C++ 코드가 다양한지 여부

<시간/>

n개의 소문자가 있는 문자열 S가 있다고 가정합니다. 문자열이 영어 알파벳의 문자가 연속적으로 있고 각 문자가 정확히 한 번만 나오는 경우에는 다양하다고 합니다. (문자 'a'와 'z'는 인접하지 않습니다). 다양한지 여부를 확인해야 합니다.

따라서 입력이 S ="fced"와 같으면 출력은 True가 됩니다.

단계

이 문제를 해결하기 위해 다음 단계를 따릅니다. −

sort the array S
flag := 1
for initialize i := 1, when i < size of S and flag is non-zero,
update (increase i by 1), do:
   if S[i] - S[i - 1] is not equal to 1, then:
      flag := 0
return (if flag is non-zero, then true, otherwise false)

예시

이해를 돕기 위해 다음 구현을 살펴보겠습니다. −

#include <bits/stdc++.h>
using namespace std;
bool solve(string S){
   sort(S.begin(), S.end());
   int flag = 1;
   for (int i = 1; i < S.size() && flag; i++)
      if (S[i] - S[i - 1] != 1)
         flag = 0;
   return flag ? true : false;
}
int main(){
   string S = "fced";
   cout << solve(S) << endl;
}

입력

"fced"

출력

1