No. 19 - Left Rotation of String

No. 19 - Left Rotation of String


Problem: Left rotation of a string is to move some leading characters to its tail. Please implement a function to rotate a string. 

For example, if the input string is “abcdefg” and a number 2, the rotated result is “cdefgab”.

Analysis: It looks difficult to get rules of left rotation on a string. Fortunately, the 7 th problem in this series “ Reverse Words in a Sentence” can give us some hints.

If we input a sentence with two words “hello world” for the problem “Reverse Words in a Sentence”, the reversed result should be “world hello”. It is noticeable that the result “world hello” can be viewed as a rotated result of “hello world”. It becomes “world hello” when we move some leading characters of string “hello world” to its ending. Therefore, this problem is quite similar to problem “Reverse Words in a Sentence”.

Let us take a string “abcdefg” as an example. We divide it into two parts: the first part contains the two leading characters “ab”, and the second part contains all other characters “cdefg”. We firstly reverse these two parts separately, and the whole string becomes “bagfedc”. It becomes “cdefgab” if we reverse the whole string, which is the expected result of left rotation with 2.

According to the analysis above, we can see that left rotation of a string can be implemented calling a Reverse function three times to reverse a segment or whole string. The sample code is shown below:

char* LeftRotateString( char* pStr,  int n)
{
     if(pStr != NULL)
    {
         int nLength =  static_cast< int>(strlen(pStr));
         if(nLength > 0 && n > 0 && n < nLength)
        {
             char* pFirstStart = pStr;
             char* pFirstEnd = pStr + n - 1;
             char* pSecondStart = pStr + n;
             char* pSecondEnd = pStr + nLength - 1;

             // Reverse the n leading characters
            Reverse(pFirstStart, pFirstEnd);
             // Reverse other characters
            Reverse(pSecondStart, pSecondEnd);
             // Reverse the whole string
            Reverse(pFirstStart, pSecondEnd);
        }
    }

     return pStr;
}

The function Reverse is shown in “ Reverse Words in a Sentence”, so we are not going to repeat it here.

The author Harry He owns all the rights of this post. If you are going to use part of or the whole of this ariticle in your blog or webpages,  please add a reference to  http://codercareer.blogspot.com/. If you are going to use it in your books, please contact me (zhedahht@gmail.com) . Thanks.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值