-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateStringbyOffset.java
More file actions
42 lines (33 loc) · 1.2 KB
/
Copy pathRotateStringbyOffset.java
File metadata and controls
42 lines (33 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.*;
public class RotateStringbyOffset {
public static void main(String[] arg) {
// Input string
String str = "abcdef";
// Convert the string to a character array
char[] A = str.toCharArray();
// Define the offset for rotation
int offset = 3;
// Calculate the length of the character array
int len = A.length;
// Ensure that the offset is within the bounds of the array
offset %= len;
// Reverse the first portion of the array
reverse(A, 0, len - offset - 1);
// Reverse the second portion of the array
reverse(A, len - offset, len - 1);
// Reverse the entire array to complete the rotation
reverse(A, 0, len - 1);
// Print the rotated array
System.out.println("\n" + Arrays.toString(A));
}
// Helper function to reverse a portion of a character array
private static void reverse(char[] str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
}