Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Java] : Adding Stack approach to check a string is palindrome or not #224

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/main/java/string/PalindromCheckSnippet.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* MIT License
*
* Copyright (c) 2017-2022 Ilkka Seppälä
* Copyright (c) 2017-2024 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
Expand All @@ -24,6 +24,9 @@

package string;

import java.util.ArrayDeque;
import java.util.Deque;

/**
* PalindromCheckSnippet.
*/
Expand Down Expand Up @@ -52,4 +55,22 @@ public static boolean isPalindrome(String s) {

return true;
}

/**
* Break the string into character array and keep iterating the stack. Then,
* While the stack is not empty and keep storing the popped elements into a StringBuilder
*/
public static boolean isPalindromeWithStack(String s) {
Deque<Character> st = new ArrayDeque<>();
char[] c = s.toCharArray();
for (char c1 : c) {
st.push(c1);
}
StringBuilder sb = new StringBuilder();
while (!st.isEmpty()) {
sb.append(st.pop());
}
return sb.toString().equals(s);
}

}
13 changes: 11 additions & 2 deletions src/test/java/string/PalindromCheckSnippetTest.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* MIT License
*
* Copyright (c) 2017-2022 Ilkka Seppälä
* Copyright (c) 2017-2024 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -45,4 +45,13 @@ void testIsPalindrome() {
assertFalse(PalindromCheckSnippet.isPalindrome("Type O Negative"));
assertFalse(PalindromCheckSnippet.isPalindrome("Foo12121Bar"));
}
}

@Test
void testIsPalindromeWithStack() {
assertTrue(PalindromCheckSnippet.isPalindromeWithStack("madam"));
assertTrue(PalindromCheckSnippet.isPalindromeWithStack("eye"));
assertTrue(PalindromCheckSnippet.isPalindromeWithStack("abbbdddbbba"));
assertFalse(PalindromCheckSnippet.isPalindromeWithStack("abbbca"));
assertFalse(PalindromCheckSnippet.isPalindromeWithStack("logic"));
}
}
Loading