问题:
编写一个Python程序,该程序接受用户对单词的输入,并使用Stack数据结构确定它是否为Palindrome。
回文是一个可以向前和向前阅读的词。回文词的一些例子是中午,思域,雷达,水平,转子,皮划艇,复活,赛车,红色,女士和参考。
以下代码是我目前所做的,需要帮助才能正确编译:
{{1}}
答案 0 :(得分:1)
Stack
的内容似乎没有人清楚,所以让我告诉你如何用collections.deque
import collections
def palindrome_checker(word):
# casefold the word, since "Racecar" is a palindrome just like "racecar"
q = collections.deque(word.casefold())
while True:
try:
l, r = q.popleft(), q.popright()
except IndexError:
# we've reached the end without error!
return True
else:
if l != r:
return False
那说python中的规范回文检查只是:
def palindrome_checker(word):
word = word.casefold() # as before
return word == word[::-1]
用[::-1]
切换一个字符串"按照相反的顺序将这个字符串给我,在每一端都是无界限的。"这相当于str(reversed(word))
答案 1 :(得分:0)
抱歉堆栈混乱
我将代码更改为以下内容,似乎正在运行:
import java.util.Scanner;
public class Text {
public static void main( String[] args){
normalizeText();
obify();
}
static void normalizeText(){
String a;
Scanner scan = new Scanner(System.in);
System.out.print("Write your String");
a = scan.nextLine();
System.out.print("String is: " + a);
a = a.replaceAll("\\W", "");
a = a.toUpperCase();
String b = a.replaceAll("\\s", "");
/* then I just return the text that the user input
but now without the spaces or punctuations. The text will also
be in all caps
*/
System.out.println("\n output String is:" + b);
/*
String c = b.replaceAll("(?i)([aeiou])", "OB$1");
System.out.println(c);
*/
}
static void obify(){
String c = b.replaceAll("(?i)([aeiou])", "OB$1");
System.out.println(c);
}
}