C++程式:檢查字串能否簡化為2022
假設我們有一個包含n位數字的數字字串S。我們對字串S執行以下操作,最多執行一次。我們選擇兩個數字i和j(1 ≤ i ≤ j ≤ n),並從S字串中刪除從位置i到j的字元。我們必須檢查字串S是否可以透過最多一次操作簡化為2022。
問題類別
為了解決這個問題,我們需要操作字串。程式語言中的字串是儲存在特定陣列式資料型別中的字元流。幾種語言將字串指定為特定資料型別(例如Java、C++、Python);而其他幾種語言將字串指定為字元陣列(例如C)。字串在程式設計中非常重要,因為它們通常是各種應用程式中首選的資料型別,並且用作輸入和輸出的資料型別。存在各種字串操作,例如字串搜尋、子串生成、字串剝離操作、字串轉換操作、字串替換操作、字串反轉操作等等。檢視下面的連結,瞭解如何在C/C++中使用字串。
https://tutorialspoint.tw/cplusplus/cpp_strings.htm
https://tutorialspoint.tw/cprogramming/c_strings.htm
因此,如果我們問題的輸入類似於S = "2548022",則輸出將為True,因為我們可以刪除索引1到3。
步驟
為了解決這個問題,我們將遵循以下步驟:
n := size of S for initialize i := 0, when i <= 4, update (increase i by 1), do: temp := (substring of S from 0 to ith character) concatenate (substring of S from index up to [n - 4 + i] if temp is same as "2022", then: return true return false
示例
讓我們看看下面的實現,以便更好地理解:
#include <bits/stdc++.h> using namespace std; bool solve(string S){ int n = S.size(); for (int i = 0; i <= 4; i++){ string temp = S.substr(0, i) + S.substr(n - 4 + i); if (temp == "2022") return true; } return false; } int main(){ string S = "2548022"; cout << solve(S) << endl; }
輸入
2548022
輸出
1
廣告