Left-hand string

Source: Internet
Author: User

Q: rotate the string left.

* Title: Define the left rotation operation of the string: Move several characters before the string to the end of the string.

* For example, if the string abcdef is rotated two places to the left to obtain the string cdefab.

* Please implement the left rotation function of the string. Requires that the complexity of the string operation with a length of n is O (n), and the auxiliary memory is O (1 ).

 

C ++ implementation:

Solution 1: do not consider the restrictions of time and space. Set the number of digits to k. Then, the system repeats k times and moves one digit at a time. The space complexity is O (1), and the time complexity is O (n * k ). If k is less than n, then O (n ^ 2 ).
Solution 2: the most direct method. Open up a memory with a size of n and copy the first k characters to the last k locations. Copy the n-k characters to the n-k position before the new space. The time complexity of this method is O (n), and the space complexity is O (n ).
Solution 3: reverse the first k characters, then reverse the last n-k characters, and finally reverse the entire string. The time complexity is O (n), and the space complexity is O (1 ).
Solution 4: refer to the rotate () method in algorithm chapter in STL source code analysis. If the string is abcdefgh, it must be shifted three places to the left. So that first points to the first element a and I = middle points to the k + 1 Element d (iterator's principle of opening, closing, and closing ).
Step 1: defabcgh (abc ends first, and the next step is the overall gh exchange between the elements after abc and def)
Step 2: defghcab (gh ends first, and the next step is to exchange c and the character (Terminator) after the original gh, which can be considered as c and AB)

Step 3: defghacb (c ends first, and the next step is to exchange Element B after c and)

Step 4: defghabc (end)
The time complexity of this method is O (n), and the space complexity is O (1 ).

Solution 1:

Abcd1234 → 4abcd123 → 34abcd12 → 234abcd1 → 1234 abcd.
RightShift (int * arr, int N, int K)
{
While (K --)
{
Int t = arr [N-1];
For (int I = N-1; I> 0; I --)
Arr [I] = arr [I-1];
Arr [0] = t;
}
}

Solution 3 Implementation:

Assume that the original array sequence is abcd1234 and the transformed array sequence is 1234 abcd, that is, four digits are shifted to the right of the loop. After comparison, it is not difficult to see that there are two segments in the same order: 1234 and abcd. we can regard these two segments as two parts. The K-bit shifting process is to swap the two parts of the array.
Perform the following steps to complete the transformation:
Sort abcd in reverse order: abcd1234 → dcba1234;
1234 in reverse order: dcba1234 → dcba4321;
All in reverse order: dcba4321 → 1234 abcd.
For pseudocode, see List 2-35.
// Code List 2-35
Reverse (int * arr, int B, int e)
{
For (; B <e; B ++, e --)
{
Int temp = arr [e];
Arr [e] = arr [B];
Arr [B] = temp;
}
}

RightShift (int * arr, int N, int k)
{
K % = N;
Reverse (arr, 0, N-K-1 );
Reverse (arr, N-K, N-1 );
Reverse (arr, 0, N-1 );
}

Another method:

In the beginning, we may have such a potential assumption: K <N. In fact, this is also true in many cases. But strictly speaking, we cannot use this "inertial thinking" to think about problems.
In programming, it is very important to fully consider the problem. K may be an integer greater than N. At this time, the above solution needs to be improved.
After carefully observing the characteristics of the right shift of the loop, it is not difficult to find that each element will return to its position after shifting N places to the right. Therefore, if K> N, the sequence of the array after right shift K-N is the same as the result of right shift K bit.

Then a general rule can be obtained:
The case after shifting K-bit right is the same as that after shifting K' = K % N-bit right, as shown in the code list 2-34.
// Code List 2-34
RightShift (int * arr, int N, int K)
{
K % = N;
While (K --)
{
Int t = arr [N-1];
For (int I = N-1; I> 0; I --)
Arr [I] = arr [I-1];
Arr [0] = t;
}
}
It can be seen that the complexity of the algorithm is reduced to O (N ^ 2) after the feature of moving the right of the loop is added. This is irrelevant to K and is a step closer to the requirement of the question. However, the time complexity is not low enough. Let's continue to explore the associations between arrays before and after the right shift of the loop.

 

Java implementation:

Public class LeftRotateString {


Public static void main (String [] args ){
String data = "abcdef ";
String re = leftRotateString (data, 2 );
System. out. println (re );
}
 
/*
* Abcdef-> AB. cdef-> ba. fedc-> cdefab
*/
Public static String leftRotateString (String str, int n ){
If (str = null | str. length () = 0 ){
Return str;
}
If (n <= 0 | n> = str. length ()){
Return str;
}
Int begin = 0;
Int end = str. length ()-1;
Char [] letters = str. toCharArray ();
ReverseString (letters, begin, n-1 );
ReverseString (letters, n, end );
ReverseString (letters, begin, end );
Return new String (letters );
 
}
 
// Public static String reverseString (String str, int begin, int end ){
Public static String reverseString (char [] letters, int begin, int end ){
/*
* Of course we can do it like this: StringBuilder sb = new
* StringBuilder (str); sb. reverse (). toString (); but we are learning
* Algorithm so let's 'reinvent the wheel '.
*/
If (begin> = end ){
Return null;
}
For (int I = begin, j = end; I <j; I ++, j --){
Char tmp = letters [I];
Letters [I] = letters [j];
Letters [j] = tmp;
}
Return new String (letters );
}
}

It is also worth mentioning that there are multiple methods to implement string inversion using java, as shown below:

Import java. util. Stack;

Public class ReverseString {

Public String reverse (String str ){
 
StringBuffer sb = new StringBuffer ();
 
For (int I = str. length ()-1; I> = 0; I --){

Sb. append (str. charAt (I ));
}
Return sb. toString ();
}

Public static String reverse1 (String s ){

Int length = s. length ();

If (length <= 1)

Return s;

String left = s. substring (0, length/2 );

String right = s. substring (length/2, length );

Return reverse1 (right) + reverse1 (left );

}

Public static String reverse2 (String s ){

Int length = s. length ();

String reverse = "";

For (int I = 0; I <length; I ++)

Reverse = s. charAt (I) + reverse;

Return reverse;

}

Public static String reverse3 (String s ){

Char [] array = s. toCharArray ();

String reverse = "";

For (int I = array. length-1; I> = 0; I --)

Reverse + = array [I];

Return reverse;

}

Public static String reverse4 (String s ){
 
Return new StringBuffer (s). reverse (). toString ();

}

Public static String reverse5 (String orig ){

Char [] s = orig. toCharArray ();

Int n = s. length-1;

Int halfLength = n/2;

For (int I = 0; I <= halfLength; I ++ ){

Char temp = s [I];

S [I] = s [n-I];

S [n-I] = temp;

}

Return new String (s );

}

Public static String reverse6 (String s ){

Char [] str = s. toCharArray ();

Int begin = 0;

Int end = s. length ()-1;

While (begin <end ){

Str [begin] = (char) (str [begin] ^ str [end]);

Str [end] = (char) (str [begin] ^ str [end]);

Str [begin] = (char) (str [end] ^ str [begin]);

Begin ++; www.2cto.com

End --;

}

Return new String (str );

}

Public static String reverse7 (String s ){

Char [] str = s. toCharArray ();

Stack <Character> stack = new Stack <Character> ();

For (int I = 0; I <str. length; I ++)

Stack. push (str [I]);

String reversed = "";

For (int I = 0; I <str. length; I ++)

Reversed + = stack. pop ();

Return reversed;

}
/*
Public String reverse8 (String str ){
Char [] cstr = str. toCharArray ();
Int n = cstr. length;
For (int I = 0; I <n/2; I ++ ){
Char temp = cstr [I];
Cstr [I] = cstr [n-i-1];
Cstr [n-i-1] = temp;
}
Return new String (cstr );
}
*/
Public static void main (String [] args ){
// String str = "abcdef ";
// System. out. println (new ReverseString (). reverse8 (str ));
}
}
Author: mingyunduoshou

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.