java中经典算法面试题
时间: 2024-01-12 10:22:42 浏览: 120
以下是Java中的经典算法面试题的一些例子:
1. 反转字符串
```java
public class ReverseString {
public static String reverse(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
public static void main(String[] args) {
String str = "Hello World";
System.out.println(reverse(str)); // 输出:dlroW olleH
}
}
```
2. 判断一个字符串是否是回文字符串
```java
public class Palindrome {
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String str = "level";
System.out.println(isPalindrome(str)); // 输出:true
}
}
```
3. 查找数组中的最大值和最小值
```java
public class FindMinMax {
public static void findMinMax(int[] arr) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int num : arr) {
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
}
System.out.println("Min value: " + min);
System.out.println("Max value: " + max);
}
public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 7};
findMinMax(arr); // 输出:Min value: 1,Max value: 9
}
}
```
阅读全文