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+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告