GeeksforGeeks » Interview Questions
Microsoft Interview Question for Software Engineer/Developer about Strings
(7 posts)-
Given a sentence, count the palindromes inside the sentence. Do not consider the palindromes inside a palindrome. Write test cases.
-
Extract individual words and check for palindrome ...
-
i could just think of 1 solution..
void check_palindrome(char*,int,int) // takes in the array,start and final positions of the array and checks for palindrome and increases the counter accordingly.
for(int i=0;i<strlen(s);i++)
{
for(int j=i+1;j<strlen(s);j++)
{
check_palindrome(s,i,j);
}
}can do this in O(n^2).
-
what about using one stack and one queue?
store the chars into the stack and queue while going through the sentence. When catch a space, pop the element from the stack and queue one by one and compare them. If finally both container are empty, we have found one palindrome, the time complexity would be O(n^2)
-
@seboy , when going with algorithm as u suggested,don't you think that we will end up with extra space complexity. Here you are storing a word in both stack as well as in queue.
Rather than doing this, just take an array and maintain a top variable.
when a space is encountered, start comparing first and last character until one of the following situations occur. first++;top--
1) when first and last characters are not same.( not a palindrome)
2) first>last. ( indicates a palindrome )Keep a counter to keep track of number of palindromes seen so far.
-
Make Suffix tree of Sentence s and its reverse and make LCA queries to know all palindrome within sentence
-
@iictarpit, What id LCA??
Reply
You must log in to post.