Java 字符串左旋转和右旋转程序


旋转意味着我们将字符向前或向后移动。向前移动意味着右旋转(或逆时针),向后移动意味着左旋转(或顺时针)。

在这个问题中,我们给定一个大小为 n 的字符字符串和一个整数 d。这里 d 小于 n。我们的任务是打印通过整数 d 左旋转或右旋转的字符串。

只有当前字符串的排列发生变化,给定字符串中字符的长度或频率不会改变。

输入 1

str = “apple”, d = 2

输出 1

Left Rotation = “pleap”
Right Rotation = “leapp”

方法

我们已经看到了上面给定字符串和整数的示例,让我们来看一下方法

方法 1:子字符串方法

这种方法的思路是:使用反转方法旋转字符串。

对于左旋转:首先,添加字符串的最后 n-d 个字符,然后添加字符串的前 d 个字符。

对于右旋转:需要将字符串和字符串大小减去 d 传递给 forLeftRotation 函数以获得右旋转字符串。

示例

import java.util.*;
import java.io.*;
public class Rotation{
    // In-place rotation of string str by d to the left.
    static String forLeftRotation(String str, int d)  {
       String first = str.substring(d);
       String second = str.substring(0, d);
       String res = first + second ;
       return res;
    } 
    // In-place rotation of string 'str' by d to the right.
    static String forRightRotation(String str, int d) {
       int n = str.length();
       int newD = n-d;
       return forLeftRotation(str, newD);
    } 
    public static void main(String args[]) {
       String str = "apple"; //given string
       int d = 2; //given integer         
       String strL = str; // store given string for left rotation
       //Call the function to rotate the string toward the left
       strL = forLeftRotation(strL, d);
       System.out.println("Left Rotation: "+strL);        
       String strR = str; // store given string for right rotation
       //Call the function to rotate the string toward the right
       strR = forRightRotation(strR, d);
       System.out.println("Right Rotation: "+strR);            
   }
}

输出

Left Rotation: pleap
Right Rotation: leapp

方法 2:使用扩展字符串

这个概念是我们可以使用一个扩展字符串(长度是常规字符串的两倍)来旋转字符串。使用扩展字符串从索引 d 到索引 len(string) + d 进行左旋转。对于右旋转,将字符串传递给 forLeftRotation 函数以将字符串左旋转字符串大小减去 d。

示例

import java.io.*;
import java.util.*;  
public class Rotation{  
   // rotation of string str by d to the left
   static String forLeftRotation(String str, int d)  {
      String temp = str + str; // Extended string
      int idx = str.length(); // Constructing a new rotated string's index   
      String leftFirst = temp.substring(d, d + idx);    
      return leftFirst; // return left rotated string
   } 
   // Rotating the string str using extended string by d
   static String forRightRotation(String str, int d) {
      return forLeftRotation(str, str.length() - d);
   }
   public static void main(String args[])  {
      String str = "apple"; 
      int d = 2;         
      String strL = forLeftRotation(str, d);
      System.out.println("Left Rotation: "+strL);       
      String strR = forRightRotation(str, d);
      System.out.println("Right Rotation: "+strR);
   }
}

输出

Left Rotation: pleap
Right Rotation: leapp

方法 3:使用双端队列

此方法定义了两种基于双端队列的方法来将字符串向左和向右旋转。函数 forLeftRotation() 和 forRightRotation() 分别将字符串 str 向左和向右旋转 d 个位置。这两个函数都返回旋转后的字符串。

示例

import java.io.*;
import java.util.*;  
public class Rotation{
   // create function to rotated string towards left
   static String forLeftRotation(String str, int d)   {
      // Create Deque to store characters of the string
      Deque<Character> dq
      = new ArrayDeque<Character>();
      for (char ch : str.toCharArray()) {
         dq.add(ch);
      }
      // first d character of the string is rotated left using deque
      for (int i = 0; i < d; i++) {
         dq.addLast(dq.removeFirst());
      } 
      // convert deque to string
      StringBuilder leftStr = new StringBuilder();
      for (char ch : dq) {
         leftStr.append(ch);
      }
      return leftStr.toString();
   }
   // create function to rotated string towards right
   static String forRightRotation(String str, int d) {
      // Create Deque to store characters of the string
      Deque<Character> dq
      = new ArrayDeque<Character>();
      for (char ch : str.toCharArray()) {
          dq.add(ch);
      } 
      // first d character of the string is rotated right using deque
      for (int i = 0; i < d; i++) {
         dq.addFirst(dq.removeLast());
      } 
      // convert deque to string
      StringBuilder rightStr = new StringBuilder();
      for (char ch : dq) {
         rightStr.append(ch);
      }
      return rightStr.toString();
   }  
   public static void main(String args[]) {
      String str = "apple"; 
      int d = 2;          
      String strL = forLeftRotation(str, d);
      System.out.println("Left Rotation: "+strL);        
      String strR = forRightRotation(str, d);
      System.out.println("Right Rotation: "+strR);
   }
}

输出

Left Rotation: pleap
Right Rotation: leapp

上述所有 3 种方法的说明

在上述所有 3 种方法中,我们给定的 'd' 或旋转次数都小于字符串的大小,如果 d 大于字符串的大小,则上述代码将报错。但为了安全起见,我们始终可以这样做:

d = d % (str.length())

结论

这里讨论了 Java 字符串左旋转和右旋转程序。实现了三种方法来解决这个问题。它们分别是子字符串方法、扩展字符串方法和双端队列方法,所有方法的时间复杂度均为 O(N)。

更新于:2023年7月11日

2K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.