檢查字串是否包含連續字母,並且每個字母只出現一次
簡介
在 C++ 中,字串是一系列字元,這些字元可能是不同的,也可能是重複的。連續字元是指同時出現的字元,其位置差為 1。例如,字元 a 和 b 是連續的,因為它們一起出現。但是,字元 m 和 o 的位置差為 2,因此它們在本質上是非連續的。
在這篇文章中,我們將開發一個程式碼,它以字串作為輸入,如果字串中的所有字元都是連續的,則顯示 true。讓我們看下面的例子來更好地理解這個主題。
示例
示例 1 - str - “pqsr”
輸出 - 是
在這篇文章中,我們將開發一個程式碼來從字串中提取當前字元和前一個字元。然後進一步檢查,如果字元的位置差值不等於 1,則返回布林值 false。
語法
sort()
sort(str.begin(), str.end())
C++ 中的 sort() 方法用於按升序排列字串中的字元,從開頭到結尾。
引數
str - 輸入字串
end - 字串中出現的最後一個字元
begin - 字串中出現的第一個字元
length()
C++ 中的 length() 方法用於計算字串中字元的數量。
str.length()
引數
str - 輸入字串
演算法
接受輸入字串 str 作為輸入。
使用 sort() 方法對輸入字串進行排序。
使用 for 迴圈 i 對字串進行迭代。
使用 length() 方法計算字串的長度並將其儲存在 len 變數中。
對字串執行 for 迴圈迭代 i。
每次都提取第 i 個位置的字元 ch 和第 i-1 個位置的字元 ch1。
如果這兩個字元之間的差值不等於 1,則返回布林值 false。
如果所有對應的字元都滿足要求的條件,則返回布林值 true。
此值以布林標誌 res 的形式返回。如果其值為 true,則列印字串包含連續字元。
示例
以下 C++ 程式碼片段用於將示例字串作為輸入,並計算字串中出現的所有字元在本質上是否連續:
//including the required libraries
#include <bits/stdc++.h>
using namespace std;
//function to check of characters consecutive
bool validateString(string str) {
//length of the string
int len = str.length();
// sorting the given string
sort(str.begin(), str.end());
// Iterate for every index and
// check for the condition
for (int i = 1; i < len; i++) {
//extract characters at the required pos
char ch = str[i];
char ch1 = str[i-1];
if (ch-ch1 != 1)
//in case characters are not consecutive
return false;
}
//if condition holds
return true;
}
//calling the main method
int main() {
// 1st example
string str = "mpon";
cout << "Input String : " <<str << " \n";
bool res = validateString(str);
if (res)
cout << "Yes, the string contains only consecutive characters\n";
else
cout << "No, the string doesn't contain only consecutive characters.\n";
return 0;
}
輸出
Input String − mpon Yes, the string contains only consecutive characters
結論
字串中持續出現的字元是同時出現的字母。這可以透過對字串從頭到尾進行排序來實現。可以很容易地比較連續位置的字元,並檢查它們相差多少位置。這可以用來獲取字串是否是連續的資訊。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP