java算法面试题及答案
时间: 2023-08-23 14:05:41 浏览: 182
以下是几个Java算法面试题及答案,供参考:
1. 逆序输出字符串
```java
public static void reverseString(String str) {
if (str == null || str.length() <= 1) {
System.out.println(str);
} else {
System.out.print(str.charAt(str.length()-1));
reverseString(str.substring(0, str.length()-1));
}
}
```
2. 查找数组中的最大值和次大值
```java
public static void findMaxAndSecondMax(int[] arr) {
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
secondMax = max;
max = arr[i];
} else if (arr[i] > secondMax && arr[i] != max) {
secondMax = arr[i];
}
}
System.out.println("Max: " + max);
System.out.println("Second Max: " + secondMax);
}
```
3. 链表反转
```java
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
```
4. 判断字符串是否为回文字符串
```java
public static boolean isPalindrome(String s) {
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
```
阅读全文