-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome_MiS.java
More file actions
74 lines (71 loc) · 2.65 KB
/
Palindrome_MiS.java
File metadata and controls
74 lines (71 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.Scanner;
import java.util.StringTokenizer;
/*
Create a system using a stack and a queue to test whether a given string is a palindrome (i.e., the characters read the same forward or backward).
mseskar
10/17/17
*/
public class Palindrome_MiS{
public static void main(String [] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter a string to see if it is a palindrome: ");
String input = s.nextLine();
if(input.length()%2 ==0){
isPalindrome(input);
}
else{
String inputEven = input.substring(0,input.length()/2) + input.substring(input.length()/2+1);
isPalindrome(inputEven);
}
}
public static String isPalindrome(String input){
String st2 = input.substring(input.length()/2);//second half of the string for the stack
String st1 = input.substring(0, input.length()/2);//first half of the string for the queue
Queue que = new Queue(); //creates the queue with default constructor
ArrayStackOfStrings stack = new ArrayStackOfStrings(input.length()/2); //stack with half the lenght of the palindrome, second half
for(int i=0; i<st1.length(); i++){
String add = st1.substring(i, i+1);
que.enqueue(add);//enqueue the first part of the String
}
for(int i=0; i<st2.length(); i++){
String add = st2.substring(i, i+1);
stack.push(add);//push the last part of the second string
}
boolean isPalin = true;
String sString = "";
String qString = "";
int count = 0;
while(isPalin && (que.size() != 0)){
qString = que.dequeue();
count++;
sString = stack.pop();
if(sString.equals(qString)) {
continue;
}
else isPalin = false;
}
if(isPalin){
String yes = "It is a palindrome";
System.out.println(yes);
return yes;
}
else{
String no = "It is not a palindrome";
System.out.println(no);
return no;
}
}
}
//$ java Palindrome_MiS
//Enter a string to see if it is a palindrome:
//potop
//It is a palindrome
//Milos@Milos-PC MINGW64 ~/Documents/+PHS/Algo (master)
//$ java Palindrome_MiS
//Enter a string to see if it is a palindrome:
//poppoa
//It is not a palindrome
//Milos@Milos-PC MINGW64 ~/Documents/+PHS/Algo (master)
//$ java Palindrome_MiS
//Enter a string to see if it is a palindrome:
//poootooop