C++ Program to check string is strictly alphabetical or not


Suppose we have a string S with n letters in lowercase. A string is strictly alphabetical string, if it follows the following rule −

  • Write an empty string to T

  • Then perform the next step n times;

  • At the i-th step take i-th lowercase letter of the Latin alphabet and insert it either to the left of the string T or to the right of the string T (c is the i-th letter of the Latin alphabet).

We have to check whether S is strictly alphabetical string or not.

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.

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

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

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

Steps

To solve this, we will follow these 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 to get 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] - '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;
}

Input

"ihfcbadeg"

Output

1

Updated on: 08-Apr-2022

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements