一個程式來檢查字串是否是彼此的旋轉?


在這裡,我們將看到一個程式,它可以判斷兩個字串是否互為旋轉。字串的旋轉就像:

假設有兩個字串 S1 = ‘HELLO’,S2 = ‘LOHEL’ 因此它們互為旋轉。將 HELLO 向左旋轉三個位置,它將變成 LOHEL。

為了解決這個問題,我們將第一個字串與自身連線起來,然後檢查第二個字串是否出現在連線後的字串中。因此對於 HELLO,它將是 HELLOHELLO。然後這個連線後的字串包含 LOHEL。[HELLOHELLO]。

演算法

isRotation(str1, str2)

begin
   if lengths of str1, and str2 are not same then return false;
   temp := concatenate str1 with str1 itself
   if temp contains str2, then
      return true
   otherwise return false
end

示例

 即時演示

#include<iostream>
using namespace std;
bool isRotation(string str1, string str2){
   if(str1.length() != str2.length())
      return false;
   string con_str = str1 + str1;
   if(con_str.find(str2) != string::npos){
      return true;
   } else {
      return false;
   }
}
main() {
   string str1, str2;
   cout << "Enter two strings: ";
   cin >> str1 >> str2;
   if(isRotation(str1, str2)){
      cout << "Two strings are rotation of each other";
   } else {
      cout << "Two strings are not rotation of each other";
   }
}

輸出

Enter two strings: STACK CKSTA
Two strings are rotation of each other

更新於: 2019-07-30

734 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.