C++程式檢查能否透過第三個字串的交換使兩個字串相等
假設我們有三個長度相同的字串S、T和U,長度為n。對於範圍0到n-1內的每個索引i,我們必須將U[i]與S[i]或T[i]交換。因此,總共執行了n次交換操作。我們必須檢查是否在執行n次操作後,我們可以使字串S與T完全相同。
因此,如果輸入類似於S = "abc";T = "bca";U = "bca",則輸出為True,因為對於所有i,如果我們將U[i]與S[i]交換,它將是"bca",而T已經是"bca"。
步驟
為了解決這個問題,我們將遵循以下步驟:
for initialize i := 0, when S[i] is non-zero, update (increase i by 1), do: if S[i] is not equal to U[i] and T[i] is not equal to U[i], then: return false return true
示例
讓我們看看下面的實現,以便更好地理解:
#include <bits/stdc++.h> using namespace std; bool solve(string S, string T, string U) { for (int i = 0; S[i]; ++i) if (S[i] != U[i] && T[i] != U[i]) return false; return true; } int main() { string S = "abc"; string T = "bca"; string U = "bca"; cout << solve(S, T, U) << endl; }
輸入
"abc", "bca", "bca"
輸出
1
廣告