文章目录
- 题目1
- 题目2
- 题目3
- 题目4
题目1
使用 StringBuilder 模拟栈的行为,通过判断相邻2个字符
是否相同,如果相同就进行删除
public class Main {
public static String fun(String s) {
if (s == null || s.length() <= 1) return s;
StringBuilder builder = new StringBuilder(); // 使用StringBuilder模拟栈
for (char c : s.toCharArray()) {
if (builder.length() > 0 && builder.charAt(builder.length() - 1) == c) {
builder.deleteCharAt(builder.length() - 1);
} else {
builder.append(c);
}
}
return builder.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
System.out.println(fun(s));
}
}
题目2
public class Main {
public static int climbStairs(int n) {
if (n <= 2) {
return n;
}
int[] dp = new int[n + 1]; // 动态规划数组
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2]; // 状态转移方程
}
return dp[n];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(climbStairs(n));
}
}
题目3
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int n = N;
ArrayList<Integer> list = new ArrayList<>(N);
while (n > 0) {
list.add(scanner.nextInt());
n -= 1;
}
ArrayList<Integer> list1 = new ArrayList<>(N);
for (int i = 0; i < N; i++) {
list1.add(0);
}
int res = 0;
// 每次从每个口袋中取列表中最小值个糖果(0不管)
while (!list1.equals(list)) {
int min = Integer.MAX_VALUE;
for (Integer i : list) {
if (i == 0) continue;
if (i < min) min = i;
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 0) continue;
list.set(i, list.get(i) - min);
}
res+=1;
}
System.out.println(res);
}
}
题目4
输入示例:
5
1 -2 3 -4 5
输出示例:
15
思路很简单,但是当时做题提交的时候,通过率总是18%。不知道为啥,后面我改成了Long类型,然后就通过了全部用例。(易错1:第一次提交没考虑0的情况)
// 这个是笔试通过的代码 当然优化之处很多
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int n = N;
ArrayList<Long> list = new ArrayList<>(N);
while (n > 0) {
list.add(scanner.nextLong());
n -= 1;
}
if (list.size() == 1) {
System.out.println(list.get(0));
return;
}
int cnt = 0;// 统计负数个数(0也算入)
int zero = 0;
for (Long i : list) {
if (i == 0) zero = 1;
if (i <= 0) {
cnt += 1;
}
}
Long res = 0L;
Long min = Long.MAX_VALUE;
for (Long i : list) {
res += Math.abs(i);
if (min > Math.abs(i)) min = Math.abs(i);
}
if (zero != 0) {
System.out.println(res);
return;
}
if ((cnt & 1) == 1) {
// 奇数个负数
res = res - min - min;
}
System.out.println(res);
}
}