657. Judge Route Circle

来源:互联网 发布:如何搜索二次元软件 编辑:程序博客网 时间:2024/06/03 02:27

题目描述

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L(Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

例子:

Example 1:

Input: "UD"Output: true

Example 2:

Input: "LL"Output: false

最初的想法,太复杂了,哈哈

public class Solution {

    public bool JudgeCircle(string moves) {
      int[] a=new int[moves.Length];
      int[] b=new int[moves.Length];
      for(int i=0;i<moves.Length;i++)
      {
          if(moves[i]=='L'){
              a[i]=-1;
          }
          else if(moves[i]=='R')
          {
              a[i]=1;
          }
          else if(moves[i]=='U')
          {
              b[i]=1;
          }
          else if(moves[i]=='D')
          {
              b[i]=-1;
          }
      }
        int sum1=0,sum2=0;
      for(int i=0;i<moves.Length;i++)
      {
          sum1+=a[i];
      }
        for(int i=0;i<moves.Length;i++)
      {
            sum2+=b[i];
      }   
        if(sum1==0 && sum2==0)
        {
            return true;
        }
        else
        {
            return false;
        }
     }

}

参考一下后的想法

public class Solution {
    public bool JudgeCircle(string moves) {
        int i=0,j=0;
        for(int k=0;k<moves.Length;k++)
        {
            switch(moves[k])
            {
                case 'U':
                    i++;
                    break;
                case 'D':
                    i--;
                    break;
                case 'R':
                    j++;
                    break;
                case 'L':
                    j--;
                    break;
            }
        }
        if(i==0&&j==0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


原创粉丝点击