i want to any other efficient way to find the palindrome of string other than using stack data structure. this is code i have written using stack operation.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package StringRevUsingStack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StringReverseThroughStack {
// private data members;
private String InputStr;
private String OutputStr;
//Constructor
public StringReverseThroughStack(String ip){
InputStr = ip;
}
public String doReverse(){
Stack theStack = new Stack(InputStr.length());
String revStr;
for(int i=0;i<InputStr.length();i++)
{
theStack.push(InputStr.charAt(i));
}
revStr="";
while(!theStack.isEmpty()){
revStr+=theStack.pop();
}
return revStr;
}
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String:");
String ip=br.readLine();
StringReverseThroughStack theStr = new StringRev开发者_StackOverflow社区erseThroughStack(ip);
String op=theStr.doReverse();
if(ip.compareTo(op)==0)
System.out.println("It is a palindrome");
else
System.out.println("It is a not palindrome");
}
}
class Stack{
private int maxSize;
private char[] stackArray;
private int Top;
public Stack(int max){
maxSize = max;
stackArray = new char[maxSize];
Top=-1;
}
public void push(char item){
stackArray[++Top]=item;
}
public char pop(){
return stackArray[Top--];
}
public char peek(){
return stackArray[Top];
}
public boolean isEmpty(){
return (Top == -1);
}
}
StringBuffer
has a reverse()
method. That should be all you need.
You could do this just with a simple for loop iterating over the string in reverse.
(Assuming java)
public String ReverseThisString(String inputStr) {
String outputStr = new String();
for(int i = inputStr.length() - 1; i >= 0; --i) {
outputStr += String.valueOf(inputStr.charAt(i));
}
return outputStr;
}
精彩评论