30-Day Leetcoding Challenge Day14

本题提供两种解法:

第一种:用left 和 right 分别统计向左或向右移动的步数。关键在于要对字符串长度求余数

第二种:把移动看作是一个环状,只需要用left记录即可,向左移动left加,向右移动left-right。

Math.floorMod与%的区别

floorMod(4, 3) == 1;   and (4 % 3) == 1
floorMod(+4, -3) == -2;   and (+4 % -3) == +1
floorMod(-4, +3) == +2;   and (-4 % +3) == -1
floorMod(-4, -3) == -1;   and (-4 % -3) == -1

 

JAVA

class Solution {
    public String stringShift(String s, int[][] shift) {
        int left = 0;
        int right = 0;
        String res = "";
        for(int[] path: shift){
            if(path[0] == 0) left += path[1];
            else right += path[1];
        }
        left = left % s.length();
        right = right % s.length();
        if(left == right)return s;
        int direction = left > right? 0:1;
        if(direction==1){
            res = s.substring(s.length()-(right-left))+s.substring(0,s.length()-(right-left));
        }
        else{
            res = s.substring(left-right)+s.substring(0,left-right);
        }
        return res;
    }
}

 

class Solution {
    public String stringShift(String s, int[][] shift) {
        int left = 0;
        String res = "";
        for(int[] path: shift){
            if(path[0] == 0) left += path[1];
            else left -= path[1];
        }
        left = Math.floorMod(left, s.length()); //取模
        res = s.substring(left)+s.substring(0,left);
        return res;
    }
}

 

Python3

class Solution:
    def stringShift(self, s: str, shift: List[List[int]]) -> str:
        left = 0
        right = 0
        res = ""
        for path in shift:
            if path[0] == 0:
                left += path[1]
            else:
                right += path[1]
        left = left % len(s) #bug刚开始没有求余数
        right = right % len(s)
        if left == right:
            return s
        direction = 0 if left > right else 1
        if direction:
            res = s[len(s)-(right-left):]+s[0:len(s)-(right-left)]
        else:
            res = s[(left-right):]+s[0:(left-right)]
        return res

 

class Solution:
    def stringShift(self, s: str, shift: List[List[int]]) -> str:
        left = 0
        res = ""
        for path in shift:
            if path[0] == 0:
                left += path[1]
            else:
                left -= path[1]
        left = left % len(s) #bug刚开始没有求余数
        res = s[left:]+s[0:left]
        return res

 

posted @ 2020-04-17 12:08  yawenw  阅读(94)  评论(0编辑  收藏  举报