软件测试面经 | 编程语言 — 检验回文
- 考察点:编程语言
- 难度:简单
- 题目:给定一个字符串,请编写程序代码来检查该字符串是否为回文。回文是指正着读和反着读都一样的词语或句子。
例如,字符串 “racecar” 和 “level” 都是回文,而 “hello” 不是。
提供一个 Java/Python 方法来检查给定字符串是否为回文。
public class PalindromeChecker {
public static boolean isPalindrome(String str) {
// 将输入字符串转为小写并去除非字母和数字的字符
String cleanedStr = str.toLowerCase().replaceAll("[^a-z0-9]", "");
// 使用双指针法检查是否为回文
int left = 0;
int right = cleanedStr.length() - 1;
while (left < right) {
if (cleanedStr.charAt(left) != cleanedStr.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String str1 = "A man a plan a canal Panama";
String str2 = "Hello World";
String str3 = "Madam, in Eden I'm Adam.";
System.out.println(str1 + " is palindrome: " + isPalindrome(str1));
System.out.println(str2 + " is palindrome: " + isPalindrome(str2));
System.out.println(str3 + " is palindrome: " + isPalindrome(str3));
}
}
#软件测试#
腾讯成长空间 6062人发布