假设我们有一个包含 n 个小写字母的字符串 s。如果字符串遵循以下规则,则它是严格的字母字符串 -
将空字符串写入 t
然后执行下一步n次;在第i步,取出拉丁字母表中的第i个小写字母,并将其插入到字符串 t 的左侧或字符串 t 的右侧(c 是拉丁字母表中的第 i 个字母)。
我们必须检查 s 是否严格是否按字母字符串排列。
问题类别要解决这个问题,我们需要操作字符串。编程语言中的字符串是存储在特定的类似数组的数据类型中的字符流。多种语言将字符串指定为特定数据类型(例如 java、c++、python);和其他几种语言将字符串指定为字符数组(例如 c)。字符串在编程中很有用,因为它们通常是各种应用程序中的首选数据类型,并用作输入的数据类型和输出。有各种字符串操作,例如字符串搜索、子字符串生成、字符串剥离操作、字符串翻译操作、字符串替换操作、字符串反向操作等等。查看下面的链接以了解字符串如何用于 c/c++ 中。
https://www.tutorialspoint.com/cplusplus/cpp_strings.htm
https://www.tutorialspoint.com/cprogramming/c_strings。 htm
因此,如果我们问题的输入类似于 s = ihfcbadeg,那么输出将为 true。
步骤要解决这个问题,我们将遵循以下步骤 -
len := size of sfor initialize i := len, when i >= 1, update (decrease i by 1), do: if s[l] is the i th character, then: (increase l by 1) otherwise when s[r] is the ith character, then: (decrease r by 1) otherwise come out from the loopif i is same as 0, then: return trueotherwise return false
示例让我们看看以下实现,以便更好地理解 -
#include <bits/stdc++.h>using namespace std;bool solve(string s){ int len = s.size(), l = 0, r = len - 1, i; for (i = len; i >= 1; i--){ if (s[l] - 'a' + 1 == i) l++; else if (s[r] - 'a' + 1 == i) r--; else break; } if (i == 0) return true; else return false;}int main(){ string s = "ihfcbadeg"; cout << solve(s) << endl;}
输入"ihfcbadeg"
输出1
以上就是c++程序检查字符串是否严格按字母顺序排列的详细内容。