美文网首页
[python] 2019-02-22

[python] 2019-02-22

作者: 原来是酱紫呀 | 来源:发表于2019-02-22 20:35 被阅读0次

    .657. Robot Return to Origin
    .942. DI String Match


    657. Robot Return to Origin

    1)Description

    There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

    The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

    Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

    Example 1:

    Input: "UD"
    Output: true
    Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

    2) Solution

    class Solution:
        def judgeCircle(self, moves: 'str') -> 'bool':
            sum1=sum2=0
            for i in moves:
                if i == 'U': sum1 += 1
                elif i == 'D': sum1 -= 1
                elif i == 'L': sum2 += 1
                elif i == 'R': sum2 -= 1
            return sum1==sum2==0
    

    942. DI String Match

    1) Description

    Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length.

    Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1:

    If S[i] == "I", then A[i] < A[i+1]
    If S[i] == "D", then A[i] > A[i+1]

    Example 1:

    Input: "IDID"
    Output: [0,4,1,3,2]

    Example 2:

    Input: "III"
    Output: [0,1,2,3]

    2) Solution

    class Solution:
        def diStringMatch(self, S: 'str') -> 'List[int]':
            A=[]
            res1=0
            res2=len(S)
            for i in S:
                if i == 'I':
                    A.append(res1)
                    res1 += 1
                elif i =='D':
                    A.append(res2)
                    res2 -= 1
            return A + [res1]
    

    得得瑟一下,,,,一生中的骄傲

    相关文章

      网友评论

          本文标题:[python] 2019-02-22

          本文链接:https://www.haomeiwen.com/subject/emcyyqtx.html