[String][6]Lintcode1790. Rotate String II

这篇博客介绍了Lintcode1790问题的解决方案,即如何根据给定的左右偏移量旋转字符串。通过计算总偏移量,确定字符串是向左还是向右移动,并相应地拼接字符串的子串来实现旋转。提供了详细的代码实现,包括判断和处理不同偏移情况的逻辑。

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

Lintcode 1790. Rotate String II

描述

Given a string(Given in the way of char array), a right offset and a left offset, move the string according to the given offset and save it in a new result set. (left offest represents the offset of a string to the left,right offest represents the offset of a string to the right,the total offset is calculated from the left offset and the right offset, split two strings at the total offset and swap positions)。

Example 1:
Input:str ="abcdefg", left = 3, right = 1
Output:"cdefgab"
Explanation:The left offset is 3, the right offset is 1, and the total offset is left 2. Therefore, the original string moves to the left and becomes "cdefg"+ "ab".
Example 2:
Input:str="abcdefg", left = 0, right = 0
Output:"abcdefg"
Explanation:The left offset is 0, the right offset is 0, and the total offset is 0. So the string remains unchanged.
Example 3:
Input:str = "abcdefg",left = 1, right = 2
Output:"gabcdef"
Explanation:The left offset is 1, the right offset is 2, and the total offset is right 1. Therefore, the original string moves to the left and becomes "g" + "abcdef".
Solution1:
public class Solution {
    /**
     * @param str: A String
     * @param left: a left offset
     * @param right: a right offset
     * @return: return a rotate string
     */
    public String RotateString2(String str, int left, int right) {
        // write your code here
        /*
        题解:
        利用左偏移量减去右偏移量得到offset。
        如果总偏移量为正数,说明字符串向左移动,A表示offset左边的字符串,B表示offset右边的字符串,返回A + B
        如果总偏移量为负数,说明字符串向右移动,A表示从右边算起offset位置处左边的字符串,B表示其右边的字符串,返回B + A
        返回 B + A,实质是两段子串的位置交换
        */
        if(str.length() == 0 || str == null) return str;
        
        int len = str.length();
        
        int offset = (left - right)%len ;
        //int offset = left - right;
        //if left and right is too large, we don't need to move so many times;
        //and the bound of the index may out of bounds
        
        String newStr = new String();
        String leftStr = new String();
        String rightStr = new String();
        
        if(offset >= 0 ){//整体需要左移
            leftStr = str.substring(offset,len);
            rightStr = str.substring(0, offset);
            newStr = leftStr + rightStr;
            
        }else{//整体需要右移
            offset = Math.abs(offset);
            leftStr = str.substring(0,len - offset);
            rightStr = str.substring(len - offset,len);
            newStr = rightStr + leftStr ;
        }
        
        return newStr;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值