Home  >  Article  >  Backend Development  >  C++ program to check if string is strictly in alphabetical order

C++ program to check if string is strictly in alphabetical order

WBOY
WBOYforward
2023-09-05 17:01:261311browse

C++ program to check if string is strictly in alphabetical order

Suppose we have a string S containing n lowercase letters. A string is a strictly alphabetical string if it follows the following rules -

  • Write the empty string to T

  • and execute the following One step n times;
  • At the i-th step, take out the i-th lowercase letter in the Latin alphabet and insert it into The left side of string T or the right side of string T (c is the ith letter of the Latin alphabet).

We have to check if S is strictly in alphabetical string order.

Problem Category

To solve this problem, we need to manipulate strings. Strings in programming languages ​​are A stream of characters stored in a specific array-like data type. multilingual Specify strings as specific data types (e.g. Java, C, Python); and several other languages Specify the string as a character array (such as C). Strings are useful in programming because they Often the preferred data type in a variety of applications and used as an input data type and output. There are various string operations such as string search, substring generation, String stripping operation, string translation operation, string replacement operation, string Reverse operation and so on. Check out the link below to see how strings Used in C/C.

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.tutorialspoint.com/cprogramming/c_strings. htm

So if the input to our problem is something like S = "ihfcbadeg", then the output will be True.

Steps

To solve this problem we will follow the following steps-

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

Example

Let us see the following implementation for better understanding -

#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] - &#39;a&#39; + 1 == i)
         l++;
      else if (S[r] - &#39;a&#39; + 1 == i)
         r--;
      else
         break;
   }
   if (i == 0)
      return true;
   else
      return false;
}
int main(){
   string S = "ihfcbadeg";
   cout << solve(S) << endl;
}

Input

"ihfcbadeg"

Output

1

The above is the detailed content of C++ program to check if string is strictly in alphabetical order. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete