回文(palindrome):指的是从头读到尾与从尾读到头一模一样的字符串。
分别在C、Java与Python实现回文检测:
C:
#include <stdio.h> #include <stdbool.h> #include <ctype.h> #define MAX_LEN 255 int main(int argc, char *args[]){ char message[MAX_LEN]; char str[MAX_LEN]; char ch; int index = 0; printf("Please enter a message: "); while((ch = getchar()) != ' '){ if(index==MAX_LEN){ while(getchar() != ' '){ continue; } break; }else{ message[index++] = ch; } } int j = 0; for(int i = 0; i < index; i++){ ch = message[i]; if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){ str[j++] = tolower(ch); } } for(int i = 0; i < j / 2; i++){ if(str[i] != str[j-i-1]){ puts("Not a Palindrome!"); return 1; } } puts("Palindrome!"); return 0; }
Java:
import java.util.Scanner; public class Palindrome{ public static boolean isPalindrome(String raw){ String str = ""; // 只拿raw字符串里的字母,拼接到str里 for(int i = 0; i < raw.length(); i++){ char ch = raw.charAt(i); if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){ str += ch; } } // str字母全部小写化 str = str.toLowerCase(); // 判断是否为回文 int end = str.length(); for(int i = 0; i < end/2; i++){ if(str.charAt(i) != str.charAt(end-i-1)){ return false; } } return true; } public static void main(String[] args){ Scanner scanner = new Scanner(System.in); // I prefer pi! // A man, a plan, a canal: Panama! // Madam, I am Adam. System.out.printf("Enter a message: "); String str = scanner.nextLine(); if(isPalindrome(str)){ System.out.println("Palindrome!"); }else{ System.out.println("Not a palindrome!"); } } }
Python:
import string def is_palindrome(text: str) -> bool: '是否为回文' # 1、先去除标点符号以及空格,并将所有字母小写化 result = '' for i in range(len(text)): if not text[i] in string.punctuation + ' ': result += text[i].lower() print(result) # 2、判断是否为回文 n = len(result) for i in range(len(result) // 2): if result[i] != result[n-i-1]: return False return True if __name__ == '__main__': print(is_palindrome('I prefer pi.')) print(is_palindrome('A man, a plan, a canal: Panama.')) print(is_palindrome('Resistance is futile!'))