gpt4 book ai didi

java - 从 java 转换为 C++

转载 作者:行者123 更新时间:2023-12-01 15:54:15 26 4
gpt4 key购买 nike

如何将以下内容转换为 C++

public class Palindrome
{
public static void main(String args[])
{
String phrase;
Palindrome program = new Palindrome();

/*gets a phrase from the user and reads it*/
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter a phrase =>");
System.out.flush();

phrase = keyboard.readLine();

/*determines if the phrase is a palindrome and prints result*/
if(!program.isPalindrome(phrase))
System.out.println("The phrase is NOT a palindrome.");

else System.out.println("The phrase is a palindrome.");

}

public static boolean isPalindrome(String testString)
{
Stack s = new Stack();
Queue q = new Queue();
String temp = testString.toLowerCase();
for (int i = 0; i < temp.length(); i++) {
Character c = new Character(temp.charAt(i));
if (!Character.isWhitespace(c.charValue())) {
s.push(c);
q.enqueue(c);
}
}
while (!s.isEmpty()) {
Character a = (Character)s.pop();
Character b = (Character)q.dequeue();
if (!a.equals(b))
return false;
}
return true;
}
}
<小时/>
public class Queue
{
private LinkedList myList;

public Queue()
{
myList = new LinkedList();
}

/**
* This method should return null if the Queue is empty
*/
public Object deQueue()
{
return myList.removeHead();
}

public void enQueue(Object addObj)
{
myList.addTail(addObj);
}

/**
* This method should return true if the queue has no more
* elements in it
*/
public boolean isEmpty()
{
myList.resetIndex();
return (myList.getIndexedNode() == null);
}
}
<小时/>
public class Stack
{
private LinkedList myList;

public Stack()
{
myList = new LinkedList();
}

/**
* This method should return null if the Stack is empty
*/
public Object pop()
{
return myList.removeHead();
}

public void push(Object addObj)
{
myList.addHead(addObj);
}

/**
* This method should return true if the stack has no more
* elements in it
*/
public boolean isEmpty()
{
myList.resetIndex();
return (myList.getIndexedNode() == null);
}

}

最佳答案

如果这是一个有效的问题,我想我会这样做:

#include <string>
#include <iostream>

bool is_palindrome(std::string const &input) {
return input == std::string(input.rbegin(), input.rend());
}

int main() {
std::cout << "Enter a phrase =>";
std::string input;
std::getline(std::cin, input);

std::cout <<
(is_palindrome(input)
? "Phrase is a palindrome"
: "Phrase is not a palindrome");
return 0;
}

我不确定为什么你要使用堆栈或双端队列来实现此目的,但如果你这样做,标准库中的那些似乎可以很好地完成这项工作。

关于java - 从 java 转换为 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5400299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com