C++程式檢查字串是否完全由字母組成
假設我們有一個包含n個小寫字母的字串S。如果一個字串遵循以下規則,則稱其為嚴格字母順序的字串:
建立一個空字串T。
然後執行接下來的n次步驟:
在第i步,取拉丁字母表中的第i個小寫字母c,將其插入到字串T的左側或右側。
我們需要檢查S是否為嚴格字母順序的字串。
問題類別
為了解決這個問題,我們需要操作字串。在程式語言中,字串是一系列字元,儲存在特定的陣列型別資料中。許多語言將字串指定為一種特定的資料型別(例如,Java、C++、Python);而其他一些語言則將字串指定為字元陣列(例如,C)。字串在程式設計中非常重要,因為它們通常是各種應用程式的首選資料型別,並且用作輸入和輸出的資料型別。有各種字串操作,例如字串搜尋、子字串生成、字串剝離操作、字串轉換操作、字串替換操作、字串反轉操作等等。檢視下面的連結,瞭解如何在C/C++中使用字串。
https://tutorialspoint.tw/cplusplus/cpp_strings.htm
https://tutorialspoint.tw/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
廣告