
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ code to check string is diverse or not
Suppose we have a string S with n lowercase letters. A string is called diverse if it has consecutive letters of the English alphabet and each letter occurs exactly once. (letters 'a' and 'z' are not adjacent). We have to check whether it is diverse or not.
So, if the input is like S = "fced", then the output will be True.
Steps
To solve this, we will follow these steps −
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)
Example
Let us see the following implementation to get better understanding −
#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; }
Input
"fced"
Output
1
- Related Articles
- C++ code to check pattern is center-symmetrical or not
- C++ code to check given matrix is good or not
- C++ code to check given flag is stripped or not
- C++ Program to check joke programming code is generating output or not
- C++ code to check grasshopper can reach target or not
- Program to check the string is repeating string or not in Python
- C# program to check if string is panagram or not
- C++ Program to check string is strictly alphabetical or not
- Swift program to check if string is pangram or not
- Python - Check if a given string is binary string or not
- Python program to check if a string is palindrome or not
- Java Program to check if a string is empty or not
- Python program to check if the string is empty or not
- Program to check a string is palindrome or not in Python
- Program to check given string is pangram or not in Python

Advertisements