Created
March 12, 2021 13:20
-
-
Save MinSomai/e814390a9b534a4060433ac4b0069b89 to your computer and use it in GitHub Desktop.
Day 18 : Java 7 | Queues and Stacks - Hackerrank.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
public class Solution { | |
// Write your code here. | |
LinkedList<String> pushPop =new LinkedList<String>(); | |
Queue<String> enqDeq = new LinkedList<>(); | |
void pushCharacter(char ch){ | |
pushPop.add(Character.toString(ch)); | |
} | |
void enqueueCharacter(char ch) { | |
enqDeq.add(Character.toString(ch)); | |
} | |
char popCharacter(){ | |
return pushPop.removeLast().charAt(0); | |
} | |
char dequeueCharacter() { | |
return enqDeq.remove().charAt(0); | |
} | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
String input = scan.nextLine(); | |
scan.close(); | |
// Convert input String to an array of characters: | |
char[] s = input.toCharArray(); | |
// Create a Solution object: | |
Solution p = new Solution(); | |
// Enqueue/Push all chars to their respective data structures: | |
for (char c : s) { | |
p.pushCharacter(c); | |
p.enqueueCharacter(c); | |
} | |
// Pop/Dequeue the chars at the head of both data structures and compare them: | |
boolean isPalindrome = true; | |
for (int i = 0; i < s.length/2; i++) { | |
if (p.popCharacter() != p.dequeueCharacter()) { | |
isPalindrome = false; | |
break; | |
} | |
} | |
//Finally, print whether string s is palindrome or not. | |
System.out.println( "The word, " + input + ", is " | |
+ ( (!isPalindrome) ? "not a palindrome." : "a palindrome." ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment