isPalindrome | Simple palindrome checker I created in Python to mirror
kandi X-RAY | isPalindrome Summary
kandi X-RAY | isPalindrome Summary
Simple palindrome checker I created in Python to mirror a Java version for a school assignment.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Check if a string is a palindrome .
isPalindrome Key Features
isPalindrome Examples and Code Snippets
public static boolean isPalindrome(String input) {
String s = input.toLowerCase().replaceAll("[\\W_]", "");
return Objects.equals(
s,
new StringBuilder(s).reverse().toString()
);
}
private boolean isPalindrome(String word) {
return word.charAt(1) == word.charAt(0);
}
Community Discussions
Trending Discussions on isPalindrome
QUESTION
I have found a recursive solution to check whether a linked list is a palindrome:
...ANSWER
Answered 2021-Jun-11 at 09:50After the
if head
statement: Why are we returningFalse
for the first if statement, whenrecursively_check(head.next)
points toNone
? This would be okay, no? Because it simply means we've reached the end of the linked list, or am I reading this wrongly?
recursively_check(head.next)
does not "point to None
". It is a boolean: either it is True
, either it is False
. Interpret a True
as "so far it looks like a palindrome" and interpret a False
as "this definitely is not a palindrome".
This particular return False
is intended to get out of recursion with a failure that was detected deeper in the recursion call tree. Here we just pass on that message to the caller, who will do the same. It is not related to having reached the end of the list. It is triggered by a difference found deeper in the recursion tree.
For the second if statement, this kind of makes sense- in my mind it is checking the first node front_pointer and the last node head are the same?
Yes, the first time it gets executed, it is like that.
Then we are simply moving the
front_pointer
, which initially points to the head of the linked list to the next node to check?
Yes
But while I understand this, from the back end, how are we moving from the last node to the second last node?
This is taken care of by recursion. Each recursive call gets to get its own head
variable. And as we initialise it with head.next
, the deeper recursive calls will have their head
initialised further in the list.
That means that when we backtrack out of a level of recursion, we get into an execution context that has its head
variable set to a previous node than the one that the deeper call was using (as we gave it head.next
). So by merely returning out of the current execution context, we fall back to a previous value of head
, which corresponds to taking a step back in the list. But do realise that we have as many head
variables here as there are nodes in the list. They all get stacked on top of each other in the recursion call stack. By unwinding the call stack we get to work with the previous head
variable.
Finally, why do we return the recursive call
recursively_check()
? I don't see when we will reach this code- as we would have returned True or False by the time we reach here, no?
We reach this statement immediately. The function above it, is not yet executed when we arrive there. It is this statement that will start the recursion, and we need to get information from that call, and that information is what we want to return.
This is the only return
statement for isPalindrome
. The other return
statements serve recursively_check
only. They don't execute a return for isPalindrome
.
Every time we exit a nested execution of recursively_check
we have tested one more pair of nodes. If ever we find a difference in value, we start returning False
. Like explained above, this False
will from then on be the return value for all unfinished calls of recursively_check
, including the one that is made directly in isPalindrome
.
On the other hand, as long as the comparisons are equal, a True
will be returned by each nested recursively_check
call. If it turns out the comparisons were always equal, then also isPalindrome
's call to recursively_check
will get a True
back.
QUESTION
I am writing code to check whether a linked list is a palindrome:
My first question is, although my code is returning false
for the input l1=[1,2,2,1]
, when it should be returning True
, I do not know how to check where the error lies.
Normally, I could run 'print' statements to check throughout the iterations or recursions, but for the below, as it is a TreeNode, I don't know how to do this.
...ANSWER
Answered 2021-Jun-09 at 11:28My first question is, although my code is returning false for the input
l1=[1,2,2,1]
, when it should be returning True, I do not know how to check where the error lies.
The code explicitly returns False for any input that has an even size. You have a comment stating "Palindrome must have an even number of digits". But that is not true. Palindromes can be odd and even. So these lines should be removed from your code:
QUESTION
I have referred many resources but unable to understand the part about how exactly it modifies the elements in the container. I have written some code to try to understand, can anyone explain what is happening?
...ANSWER
Answered 2021-May-26 at 17:57The algorithm just moves or copies (depending on used iterators) elements equal to 'b' to positions where elements equal to 'a' are stored if this is required.
It does not swap elements of the container.
QUESTION
So, I was solving this problem of detecting a palindrome in a linked list. I came up with the following solution for it:
...ANSWER
Answered 2021-May-18 at 17:03First of all Welcome to StackOverflow!
Because of how simple this problem's solution can be I feel obligated to tell you that a solution with an auxiliary stack is not only easy to implement but also easy to understand. But since you asked why your code fails for certain cases I'll answer that question first. Your code in particular is counting the number of digits that have an odd count.
Although this seems to be what you are supposed to do to detect a palindrome notice that a linked list that looks like 1 -> 1 -> 0 -> 0 is also considered a palindrome under your code because the count is always going to be less than 0.
Your solution works for telling us if it is possible to create a palindrome given a set of digits. Suppose that the question was like "given a linked list tell me if you can rearrange it to create a palindrome" but it does not work for "is this linked list a palindrome".
QUESTION
This code give me a runtime of 269 ms, can anyone help me to reduce the complexity of this solution?
Input: left = "4", right = "1000"
Output: 4
Explanation: 4, 9, 121, and 484 are super palindrome. Note that 676 is not a super palindrome: 26 * 26 = 676, but 26 is not a palindrome.
...ANSWER
Answered 2021-May-08 at 22:28I don't understand the super palindrome
part.
But, here is a simpler implementation of isPalindrome
:
QUESTION
I'm writing a simple algorithm that checks if a string is a palindrome in javascript. This is what I have so far:
...ANSWER
Answered 2021-Apr-25 at 19:01Even if you correct the regular expression (by removing the dot), the inner while
loops may exit because you reach the end of the array, leaving you with out of range index references in the comparison that follows in the if
.
It is better to just remove the characters that are not alphanumeric, and to turn everything to lower case even before you start the loop. Furthermore, you can stop the outer loop when i
crosses over j
:
QUESTION
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
regularListHead = ListNode(-1)
regularListHead.next = head
reverseListHead = head
reverseListPrev = None
reverseListCurrent = reverseListHead
while reverseListCurrent != None:
reverseListNext = reverseListCurrent.next
reverseListCurrent.next = reverseListPrev
reverseListPrev = reverseListCurrent
reverseListCurrent = reverseListNext
reverseListHead = reverseListPrev
a = regularListHead
...ANSWER
Answered 2021-Apr-23 at 20:03You only create one new node. All the other nodes are the nodes of your original list, and you update their next
properties so the list is reversed.
So if you want to have both the original and the reversed list, you'll have to have two lists, each having their own nodes:
QUESTION
I understand other approaches such as using stack and reversing the second half of the linked list. But, what is wrong with my approach.
...ANSWER
Answered 2021-Apr-19 at 21:16The following can be said about your solution:
It fails with an exception if
head
isnull
. To avoid that, you could just remove the firstif
statement. That case does not need a separate handling. When the list is a single node, then the first iteration will execute thebreak
and so you'll gettrue
as return value. But at least you will not access->next
whenhead
isnull
It mutates the given list. This is not very nice. The caller will not expect this will happen, and may need the original list for other purposes even after this call to
isPalindrome
.It is slow. Its time complexity is quadratic. If this is part of a coding challenge, then the test data may be large, and the execution of your function may then exceed the allotted time.
Using a stack is indeed a solution, but it feels like cheating: then you might as well convert the whole list to an array and test whether the array is a palindrome using its direct addressing capabilities.
You can do this with just the list as follows:
- Count the number of nodes in the list
- Use that to identify the first node of the second half of the list. If the number of nodes is odd, let this be the node after the center node.
- Apply a list reversal algorithm on that second half. Now you have two shorter lists.
- Compare the values in those two lists are equal (ignore the center node if there was one). Remember the outcome (false or true)
- Repeat step 3 so the reversal is rolled back, and the list is back in its original state.
- Return the result that was found in step 4.
This takes linear time, and so for larger lists, this should outperform your solution.
QUESTION
I am working on implementing the longest palindromic substring problem and I followed the approach with DP and extra O(N^2)
(yes I know there is an even more efficient algorithm but I am not interested in that in this post).
My implementation which basically uses the recurrence:
ANSWER
Answered 2021-Apr-17 at 21:06I tried using c-like arrays instead of HashMap
, here is the code:
QUESTION
I have written some code below to determine is a Linked List is a palindrome, but when I run it through tests cases it simply times out. Any idea what is wrong with the code? Thanks
...ANSWER
Answered 2021-Apr-11 at 09:23Your 3rd while
statement is infinite (if curr2.val == curr.val
it will never stop)
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install isPalindrome
You can use isPalindrome like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page