使用 C++ 中追加和刪除末尾操作來實現字串之間的相互轉換
在本教程中,我們將討論一個使用追加和刪除末尾操作將一個字串轉換為另一個字串的程式。
為此,我們將提供兩個字串。我們的任務是計算是否可以透過對最後一個元素執行 k 次追加和刪除操作將第一個字串轉換為第二個字串。
示例
#include <bits/stdc++.h> using namespace std; //checking if conversion between strings is possible bool if_convert(string str1, string str2, int k){ if ((str1.length() + str2.length()) < k) return true; //finding common length of both string int commonLength = 0; for (int i = 0; i < min(str1.length(), str2.length()); i++) { if (str1[i] == str2[i]) commonLength++; else break; } if ((k - str1.length() - str2.length() + 2 * commonLength) % 2 == 0) return true; return false; } int main(){ str1 = "tutorials", str2 = "point"; k = 5; cout << endl; if (if_convert(str1, str2, k)) cout << "Yes"; else cout << "No"; return 0; }
輸出
No
廣告