8 题 Rotate String

这篇文章介绍了如何使用C++实现字符串的旋转功能,通过给定字符数组和偏移量,实现在原地进行左向右的旋转操作。代码示例详细解释了旋转过程,并针对输入边界条件进行了处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Rotate String

Description
Given a string of char array and an offset, rotate the string by offset in place. (from left to right).
In different languages, str will be given in different ways. For example, the string “abc” will be given in following ways:

Java: char[] str = {‘a’, ‘b’, ‘c’};
Python:str = [‘a’, ‘b’, ‘c’]
C++:string str = “abc”;

public class Solution {
    /**
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    public void rotateString(char[] str, int offset) {
        // write your code here
       
       
        if(str == null || str.length == 0 ){
            return   ;
        }
         offset = offset % str.length ;
         if(offset == 0){
             return ;
         }
        int len = str.length -1 ;
        char[] str1 = new char[len] ;
        char[] str2 = new char[len] ;
        for(int i = 0 ; i < len-offset+1 ; i++){
               str1[i] = str[i] ;
        }
        int count = 0 ;
        for(int j = len-offset+1 ; j <= len ; j++){
            str2[count] = str[j] ;
            count++ ;
        }
        for(int i = 0 ; i < str2.length ; i++){
            str[i] = str2[i] ;
        }
        int count1 = 0 ;
        for(int j = offset ; j <= len ; j++){
            str[j] = str1[count1] ;
            count1++ ;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值