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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP