java - JAVA:如何确定输入是否为回文?
问题描述
请使用以下方法。
我正在尝试摆脱所有空格、标点符号并使所有内容都小写。然后我想看看字符串是否是回文(从正面和背面读取时相同。
我想不通。
public static void main(String[] args) {
String word=null;
String reverse="";
Scanner console = new Scanner(System.in);
System.out.print("Please enter a word or a phrase:");
word = console.nextLine();
word=word.replaceAll("\\s+",""); //removes white space
word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
word=word.toLowerCase();
for(int i=word.length()-1; i>=0; i--) {
reverse +=word.charAt(i);
}
for(int i=0; i<word.length(); i++) {
System.out.print(word);
if(word.charAt(i) != reverse.charAt(i)) {
System.out.println("Not a Palindrome");
}else {
System.out.println("Palindrome");```
解决方案
首先,您可以将所有正则表达式组合成一个(首先使输入小写,然后消除所有不是小写字母的内容)。其次,您可以消除构建临时String
以检查它是否是回文;因为您可以迭代中的字符word
并检查正面和背面。喜欢,
System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
boolean palindrome = true;
for (int i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
palindrome = false;
break;
}
}
if (!palindrome) {
System.out.println("Not a Palindrome");
} else {
System.out.println("Palindrome");
}
如果您决定无论如何要反转word
以实现效率较低的实施。使用StringBuilder
,因为它可以在一行中完成(而且我认为它看起来更具可读性)。
System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
if (!new StringBuilder(word).reverse().toString().equals(word)) {
System.out.println("Not a Palindrome");
} else {
System.out.println("Palindrome");
}
推荐阅读
- laravel - 表单验证和检索输入值的正确顺序是什么?
- c# - 如果 sql 参数为空,则将其转换为 DBNULL 值
- php - 是什么阻止了文件上传
- java - Spring Security 中的 PostMapping
- qpid - Qpid Broker 7 是否在其配置文件中支持 ${variable} 替换?
- python - 在气流 1.10.2 的 RBAC 模式下,批量清除操作不起作用
- swift - 如何使用泛型默认参数
- javascript - 在 GraphQL 中使用查询响应类型有什么缺点?
- php - 图片上传无需刷新和更改背景
- excel - 如何验证两个单元格是否相等,如果不相等,则在上方空行并继续?