本文共 2282 字,大约阅读时间需要 7 分钟。
What is palindrome string?
什么是回文字符串?
A string is a palindrome if the string read from left to right is equal to the string read from right to left i.e. if the actual string is equal to the reversed string.
如果从左至右读取的字符串等于从右至左读取的字符串,即实际字符串等于反向字符串,则该字符串为回文 。
In the below program, we are implementing a python program to check whether a string is a palindrome or not?
在下面的程序中,我们正在实现一个python程序来检查字符串是否是回文?
Steps:
脚步:
First, find the reverse string
首先,找到反向字符串
Compare whether revers string is equal to the actual string
比较反转字符串是否等于实际字符串
If both are the same, then the string is a palindrome, otherwise, the string is not a palindrome.
如果两者相同,则该字符串是回文,否则,该字符串不是回文。
Example:
例:
Input: "Google" Output: "Google" is not a palindrome string Input: "RADAR" Output: "RADAR" is a palindrome string
Method 1: Manual
方法1:手动
# Python program to check if a string is # palindrome or not# function to check palindrome stringdef isPalindrome(string): result = True str_len = len(string) half_len= int(str_len/2) for i in range(0, half_len): # you need to check only half of the string if string[i] != string[str_len-i-1]: result = False break return result # Main codex = "Google"if isPalindrome(x): print(x,"is a palindrome string")else: print(x,"is not a palindrome string") x = "ABCDCBA"if isPalindrome(x): print(x,"is a palindrome string")else: print(x,"is not a palindrome string")x = "RADAR"if isPalindrome(x): print(x,"is a palindrome string")else: print(x,"is not a palindrome string")
Output
输出量
Google is not a palindrome stringABCDCBA is a palindrome stringRADAR is a palindrome string
Method 2: Slicing
方法2:切片
# Python program to check if a string is # palindrome or not# function to check palindrome stringdef isPalindrome(string): rev_string = string[::-1] return string == rev_string# Main codex = "Google"if isPalindrome(x): print(x,"is a palindrome string")else: print(x,"is not a palindrome string") x = "ABCDCBA"if isPalindrome(x): print(x,"is a palindrome string")else: print(x,"is not a palindrome string")x = "RADAR"if isPalindrome(x): print(x,"is a palindrome string")else: print(x,"is not a palindrome string")
Output
输出量
Google is not a palindrome stringABCDCBA is a palindrome stringRADAR is a palindrome string
翻译自:
转载地址:http://qdtzd.baihongyu.com/