题
思
leetcode134
按照规则从每一个加油站走一遍就行了。
leetcode914
做一个个数统计,然后求所有个数的最大公约数。
leetcode1249
就一个栈呗,能不能搞点有难度的题啊。
代码
leetcode134
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
for (int i = 0; i < cost.length; i++) {
if (cost[i] > gas[i]) {
continue;
}
int gasLeft = gas[i] - cost[i];
int j = (i + 1) % cost.length;
while (j != i) {
if (cost[j] > gas[j] + gasLeft) {
break;
}
gasLeft += gas[j] - cost[j];
j = (j + 1) % cost.length;
}
if (j == i) {
return i;
}
}
return -1;
}
}
leetcode914
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
Map<Integer, Integer> count = new HashMap<Integer, Integer>();
Arrays.stream(deck).forEach(a -> count.put(a, count.getOrDefault(a, 0) + 1));
int divisor = count.get(deck[0]);
for (int i : count.keySet()) {
divisor = gcd(divisor, count.get(i));
if (divisor == 1) {
return false;
}
}
return true;
}
private int gcd(int a, int b) {
int temp;
while (b > 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
}
leetcode1249
class Solution {
public String minRemoveToMakeValid(String s) {
StringBuilder sb = new StringBuilder(s);
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '(') {
stack.push('(');
}
if (sb.charAt(i) == ')') {
if (stack.isEmpty()) {
sb.deleteCharAt(i);
i--;
} else {
stack.pop();
}
}
}
int size = stack.size();
while (size > 0) {
sb.deleteCharAt(sb.lastIndexOf("("));
size--;
}
return sb.toString();
}
}