思路:想象个坐标系,x轴,y轴,拿变量x,y代替,再把字符串编程字符数组去判断
注意:字符串的长度调用 如:moves.length(),而数组是word.length,没有括号
代码1(没ac,完成60/62):
class Solution {
public boolean judgeCircle(String moves) {
int x=0,y=0;
char[] word=new char[moves.length()];
for(int i=0;i<word.length;i++){
word=moves.toCharArray();
if(word[i]=='U') y++;
if(word[i]=='D') y--;
if(word[i]=='L') x--;
if(word[i]=='R') x++;
}
return x==0&&y==0;
}
}
改进版(ac成功):class Solution {
class Solution {
public boolean judgeCircle(String moves) {
int x=0,y=0;
for(int i=0;i<moves.length();i++){
char[] word=moves.toCharArray();
if(word[i]=='U') y++;
if(word[i]=='D') y--;
if(word[i]=='L') x--;
if(word[i]=='R') x++;
}
return x==0&&y==0;
}
}
妈的,神奇!!! 难道先创建数组会耽误时间,求大神解答!!