C++程序检查字符串是否严格按字母顺序排列

WBOY
WBOY 转载
2023-09-05 17:01:26 887浏览

C++程序检查字符串是否严格按字母顺序排列

假设我们有一个包含 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 S
for 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 loop
if i is same as 0, then:
   return true
Otherwise
   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++程序检查字符串是否严格按字母顺序排列的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除