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)

示例

让我们看看以下实现以获得更好的理解 -

Open Compiler
#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; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输入

"fced"

输出

1

更新日期:2022-03-15

248 次浏览

启动你的 职业

完成课程认证

开始
广告