📌  相关文章
📜  C++ 程序检查字符串是否相互旋转 |设置 2

📅  最后修改于: 2022-05-13 01:55:38.375000             🧑  作者: Mango

C++ 程序检查字符串是否相互旋转 |设置 2

给定两个字符串s1 和 s2,检查 s2 是否是 s1 的旋转。
例子:

Input : ABACD, CDABA
Output : True

Input : GEEKS, EKSGE
Output : True

我们在之前的文章中讨论了一种将子字符串匹配作为模式处理的方法。在这篇文章中,我们将使用KMP 算法的 lps (最长专有前缀,也是后缀)构造,这将有助于找到字符串b 的前缀和字符串a 的后缀的最长匹配。通过它我们将知道旋转点,从这个点匹配字符。如果所有字符都匹配,那么它是一个旋转,否则不是。
下面是上述方法的基本实现。

C++
// C++ program to check if 
// two strings are rotations
// of each other
#include
using namespace std;
bool isRotation(string a, 
                string b)
{
  int n = a.length();
  int m = b.length();
  if (n != m)
    return false;
  
  // create lps[] that 
  // will hold the longest
  // prefix suffix values 
  // for pattern
  int lps[n];
  
  // length of the previous 
  // longest prefix suffix
  int len = 0;
  int i = 1;
    
  // lps[0] is always 0
  lps[0] = 0; 
  
  // the loop calculates 
  // lps[i] for i = 1 to n-1
  while (i < n) 
  {
    if (a[i] == b[len]) 
    {
      lps[i] = ++len;
      ++i;
    }
    else 
    {
      if (len == 0) 
      {
        lps[i] = 0;
        ++i;
      }
      else 
      {
        len = lps[len - 1];
      }
    }
  }
  
  i = 0;
  
  // Match from that rotating
  // point
  for (int k = lps[n - 1]; 
           k < m; ++k) 
  {
    if (b[k] != a[i++])
      return false;
  }
  return true;
}
  
// Driver code
int main()
{
  string s1 = "ABACD";
  string s2 = "CDABA";
  cout << (isRotation(s1, s2) ? 
           "1" : "0");
}
  
// This code is contributed by Chitranayal


输出:

1

时间复杂度: O(n)
辅助空间: O(n)

请参阅有关检查字符串是否相互旋转的完整文章 |设置2了解更多详情!