題目描述 LeetCode 657
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
中文描述
題目大意是,一個機器人現(xiàn)在在原點,然后呢,它開始走,有且僅有四個方向,上下左右,分別用字母 'U' 'D' 'L' 'R' 來表示,給你一串字符,你來判斷最后它是否返回原點,是則返回 true ,不是則返回 false。
解題思路
- 依照題意,只有四個方向,最后判斷是否返回原點,所以呢,我是不是可以把方向轉(zhuǎn)化為數(shù)字呢,我的思路是,往上走,數(shù)字計 1;往下走,數(shù)字計 -1; 往左走,數(shù)字計 -2;往右走,數(shù)字計 2. 最后數(shù)字累加為0,則機器人返回原點,不為0,則還在外面逛游呢。
- 事實證明,思路完全正確,但是數(shù)字設(shè)置有問題,為啥呢? 因為,比如 機器人左走1步,數(shù)字計 -2,然后呢,它再往上走兩步,累加為 0,哇,竟然回到原點,所以數(shù)字設(shè)置有問題,解決辦法,數(shù)字設(shè)置差距拉開,上下計數(shù)不變,左右計數(shù)分別為 -200, 200,運行通過。
C 語言代碼
bool judgeCircle(char* moves)
{
bool flag;
int length = strlen(moves);
int i = 0;
int sum = 0;
for ( i = 0; i < length; i ++ )
{
if ( moves[i] == 'U' )
{
sum += 1;
}
else if( moves[i] == 'D' )
{
sum += -1;
}
else if( moves[i] == 'L' )
{
sum += -200;
}
else
{
sum += 200;
}
}
if ( sum == 0)
{
flag = true;
}
else
{
flag = false;
}
return flag;
}
運行時間竟然排到第一,哎呀媽呀,我的小心臟真是受不了,算是對自己的鼓勵,再接再勵。
執(zhí)行結(jié)果
注意點
- 上下左右設(shè)置數(shù)值要保證,上下為相反數(shù),左右為相反數(shù),且正交方向的數(shù)值大小要拉開,避免左走一步為 -2,上走兩步為 2(往上沒走一步計數(shù) 1),此時沒在原點,卻使程序認為返回原點的情況。
小談
- 原先一直以為 C 語言不行了,畢竟現(xiàn)在都鼓吹 python,JAVA, 沒想到最近學(xué) word2vec ,發(fā)現(xiàn) word2vec 源代碼用 C 語言寫的,所以學(xué)學(xué) C 還是好的。 當然了,在全民 AI 的年代,python, JAVA 也是必須要掌握滴。