贪心
记录三种字符的个数,计算出L和R的差值的绝对值,最后加上'_'的数量,直接返回。
class Solution {
public:
int furthestDistanceFromOrigin(string moves) {
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
for (auto x : moves) {
if (x == 'L') cnt1++;
if (x == 'R') cnt2++;
if (x =='_') cnt3++;
}
return cnt1 > cnt2 ? cnt1 + cnt3 - cnt2 : cnt2 + cnt3 - cnt1;
}
};
class Solution {
public int furthestDistanceFromOrigin(String moves) {
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
char[] str = moves.toCharArray();
for (char x : str) {
if (x == 'L') cnt1++;
if (x == 'R') cnt2++;
if (x =='_') cnt3++;
}
return cnt1 > cnt2 ? cnt1 + cnt3 - cnt2 : cnt2 + cnt3 - cnt1;
}
}
func furthestDistanceFromOrigin(moves string) int {
cnt1, cnt2, cnt3 := 0, 0, 0
for i := 0; i < len(moves); i++ {
if moves[i] == 'L' {
cnt1++
}
if moves[i] == 'R' {
cnt2++
}
if moves[i] =='_' {
cnt3++
}
}
if (cnt1 > cnt2) {
return cnt1 + cnt3 - cnt2
}
return cnt2 + cnt3 - cnt1
}