📜  字符串左旋转右旋转的C++程序

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

字符串左旋转右旋转的C++程序

给定一个大小为 n 的字符串,编写函数以对字符串执行以下操作 -

  1. 向左(或逆时针)将给定的字符串旋转 d 个元素(其中 d <= n)
  2. 向右(或顺时针)将给定的字符串旋转 d 个元素(其中 d <= n)。

例子:

Input : s = "GeeksforGeeks"
        d = 2
Output : Left Rotation  : "eksforGeeksGe" 
         Right Rotation : "ksGeeksforGee"  


Input : s = "qwertyu" 
        d = 2
Output : Left rotation : "ertyuqw"
         Right rotation : "yuqwert"

一个简单的解决方案是使用临时字符串进行旋转。对于左旋转,首先复制最后 nd 个字符,然后将前 d 个字符复制到临时字符串。对于右旋转,首先复制最后 d 个字符,然后复制 nd 个字符。

我们可以同时进行原地旋转和 O(n) 时间吗?
这个想法是基于旋转的反转算法。

// Left rotate string s by d (Assuming d <= n)
leftRotate(s, d)
  reverse(s, 0, d-1); // Reverse substring s[0..d-1]
  reverse(s, d, n-1); // Reverse substring s[d..n-1]
  reverse(s, 0, n-1); // Reverse whole string.  

// Right rotate string s by d (Assuming d <= n)
rightRotate(s, d)

  // We can also call above reverse steps
  // with d = n-d.
  leftRotate(s, n-d)  

以下是上述步骤的实现:

C++
// C program for Left Rotation and Right
// Rotation of a String
#include
using namespace std;
 
// In-place rotates s towards left by d
void leftrotate(string &s, int d)
{
    reverse(s.begin(), s.begin()+d);
    reverse(s.begin()+d, s.end());
    reverse(s.begin(), s.end());
}
 
// In-place rotates s towards right by d
void rightrotate(string &s, int d)
{
   leftrotate(s, s.length()-d);
}
 
// Driver code
int main()
{
    string str1 = "GeeksforGeeks";
    leftrotate(str1, 2);
    cout << str1 << endl;
 
    string str2 = "GeeksforGeeks";
    rightrotate(str2, 2);
    cout << str2 << endl;
    return 0;
}


输出:

Left rotation:  eksforGeeksGe
Right rotation:  ksGeeksforGee                 

时间复杂度: O(N)

辅助空间: O(1)

请参阅完整的文章关于字符串的左旋转和右旋转以获取更多详细信息!