Thứ Sáu, 12 tháng 9, 2014

Problem:

Given a string , find if it is a palindrome or not. This string can contain special characters like comma hypen colon space semicolon etc. The program should ignore these special characters and find if the rest of the string is palindrome or not. Examples: 1. If the input string is "zapqa", the program should return "Not a Palindrome" 2. If the input string is "a,b-c;b^a ", the program should return "Palindrome" as it would ignore the special characters and the rest of the string abcba is a palindrome. The list of special characters that the program should ignore are `~!@#$%^&*()-_+={[}],<>?


solution:




package com.shashi;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
class stack1
{
private char mystack[],temp[];
private int length;
stack1(int length)
{
this.length=length;
mystack=new char[length];
}
private int top=-1;
void push(char ele)throws Exception
{
if(top==mystack.length-1)
{
  
temp=new char[mystack.length*2];
for(int i:mystack)
temp[i]=mystack[i];
mystack=temp;
mystack[++top]=ele;
}
else
mystack[++top]=ele;
}
public char pop()throws Exception
{

  if(top==-1)
  return ' ';
  else
  
return mystack[top--];
}
}

public class Polyndrome {

public static void main(String []args)throws Exception
{
boolean ispoly=false;
char che;
System.out.print("Enter your string:");
Scanner sc=new Scanner(System.in);
String data=sc.next();
ArrayList<Character>list=new ArrayList<Character>();
stack1 st=new stack1(data.length());
for(int i=0;i<data.length();i++)
{
if(isChar(data.charAt(i)))

list.add(data.charAt(i));

}
//copy all data from list to stack1
Iterator<Character > ite=list.iterator();
while(ite.hasNext())
{
st.push(ite.next());
}


for(int i=0;i<list.size();i++)
{
   che=list.get(i);
if(che==st.pop())
ispoly=true;
else
ispoly=false;
}

if(ispoly)
System.out.println("String is polyndrom");
else
System.out.print("String is not a palindrome");
}

public static boolean isChar(char c)
{
if((c>='a'&& c<='z') || (c>='A' && c<='Z'))
return true;
else
return false;

}

}

output:1

Enter your string:a,b-c;b^a
String is polyndrom

output 2:
Enter your string:shashi
String is not a palindrome

output:3
Enter your string:zapqa
String is not a palindrome


Không có nhận xét nào:

Đăng nhận xét