合法回文(字符串)
阿新 • • 發佈:2018-05-18
bool package flag 回文 IT scanner left 數組 結束
問題描述
給定一個字符串,判斷是不是回文字符串。只考慮字符串中的數字、字母,並且同一個字母的大寫和小寫是等價的。
例如:
A man, a plan, a canal: Panama 是回文。
race a car 不是回文。
註意:在這道題目中,我們認為空串是回文字符串。
輸入格式
輸入有多行,以 EOF 結束。每行輸入一個長度不超過 500 的字符串。
輸出格式
對於每行輸入,判斷是否是符合題目要求的回文。如果是,則輸出一行 true
;否則輸出一行 false
。
代碼
參考代碼一
package javaexam;
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while(input.hasNext())
{
boolean flag = true;
String line = input.nextLine().toLowerCase();
int left = 0;
int right = line.length () - 1;
while(left < right)
{
// 若非字母和數字,跳過
while(!isCharNum(line.charAt(left)) && left < right)
++left;
while(!isCharNum(line.charAt(right)) && left < right)
--right;
if ((left < right) && (line.charAt(left++) != line.charAt(right--)))
{
flag = false;
break;
}
}
System.out.println(flag ? "true" : "false");
}
}
// 也可用庫函數 Character.isLetter(Char) || Character.isDigit(Char)
static boolean isCharNum(char c)
{
if(('0' <= c && c <= '9') || ('a' <= c && c <= 'z'))
return true;
else
return false;
}
}
參考代碼二
import java.util.Scanner;
public class Main
{
public static void palia(String str)
{
// 把字符串str中的大寫轉小寫
str = str.toLowerCase();
// 統計字符串str中字母和數字加起來一共有多少個,以便初始化ch字符數組大小。
int count = 0;
for (int i = 0; i < str.length(); ++i)
{
char temp = str.charAt(i);
if ((temp >= '0' && temp <= '9') || (temp >= 'a' && temp <= 'z'))
{
++count;
} else
continue;
}
char[] ch = new char[count]; // 初始化字符數組ch大小為str中字母和數字的總和
// 把字符串str中的所有字符和數字依次放入字符數組中
for (int i = 0, j = 0; i < str.length(); ++i)
{
char temp = str.charAt(i);
if ((temp >= '0' && temp <= '9') || (temp >= 'a' && temp <= 'z'))
{
ch[j++] = temp;
} else
continue;
}
// 判斷字符數組ch中的內容是否滿足回文條件
for (int i = 0, j = count - 1; i < j; ++i, --j)
{
if (ch[i] == ch[j])
{
continue;
} else
{
System.out.println("false");
return;
}
}
System.out.println("true");
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while (input.hasNext())
{
String str = input.nextLine();
palia(str);
}
}
}
測試樣例
樣例一:
A man, a plan, a canal: Panama
true
樣例二:
race a car
false
合法回文(字符串)