if you want to remove an article from website contact us from top.

    given a string strstr, check if its a palindrome. consider it to be case insensitive. a palindrome string is a sequence of characters that reads the same forwards and backwards. if strstr is found to be a palindrome, print it is a palindrome else print it is not a palindrome

    Mohammed

    Guys, does anyone know the answer?

    get given a string strstr, check if its a palindrome. consider it to be case insensitive. a palindrome string is a sequence of characters that reads the same forwards and backwards. if strstr is found to be a palindrome, print it is a palindrome else print it is not a palindrome from screen.

    Check if the characters in a string form a Palindrome in O(1) extra space

    A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

    Check if the characters in a string form a Palindrome in O(1) extra space

    Difficulty Level : Medium

    Last Updated : 31 Aug, 2022

    Given string str. The string may contain lower-case letters, special characters, digits, or even white spaces. The task is to check whether only the letters present in the string are forming a Palindromic combination or not without using any extra space.

    Note: It is not allowed to use extra space to solve this problem. Also, the letters present in the string are in lower-case and the string may contain special characters, digits, or even white spaces along with lowercase letters.Examples:Input : str = “m a 343 la y a l am”Output : YES

    The characters in the string form the sequence “malayalam”, which is a palindrome.

    Input : str = “malayalam”Output : YES

    Recommended: Please try your approach on first, before moving on to the solution.

    Approach:

    Create two utility functions to get the first and last position of characters present in the string.

    Start traversing the string, and keep finding the position of the first and last characters every time.

    If the first and last characters are the same for every iteration and the string is traversed completely, then print YES, otherwise print NO.

    Below is the implementation of the above approach:

    C++

    // CPP program to check if the characters in

    // the given string forms a Palindrome in

    #include

    // O(1) extra space

    using namespace std;

    // Utility function to get the position of

    // first character in the string

    int firstPos(string str, int start, int end)

    { int firstChar = -1;

    // Get the position of first character

    // in the string

    for (int i = start; i <= end; i++) {

    if (str[i] >= 'a' && str[i] <= 'z') {

    firstChar = i; break; } } return firstChar; }

    // Utility function to get the position of

    // last character in the string

    int lastPos(string str, int start, int end)

    { int lastChar = -1;

    // Get the position of last character

    // in the string

    for (int i = start; i >= end; i--) {

    if (str[i] >= 'a' && str[i] <= 'z') {

    lastChar = i; break; } } return lastChar; }

    // Function to check if the characters in

    // the given string forms a Palindrome in

    // O(1) extra space

    bool isPalindrome(string str)

    {

    int firstChar = 0, lastChar = str.length() - 1;

    bool ch = true;

    for (int i = 0; i < str.length(); i++) {

    firstChar = firstPos(str, firstChar, lastChar);

    lastChar = lastPos(str, lastChar, firstChar);

    // break, when all letters are checked

    if (lastChar < 0 || firstChar < 0)

    break;

    if (str[firstChar] == str[lastChar]) {

    firstChar++; lastChar--; continue; }

    // if mismatch found, break the loop

    ch = false; break; } return (ch); } // Driver code int main() {

    string str = "m     a  343 la y a l am";

    if (isPalindrome(str))

    cout << "YES"; else cout << "NO"; return 0; }

    Java

    Python 3

    C#

    PHP

    Java Python 3 C# PHP Javascript

    Output

    YES

    स्रोत : www.geeksforgeeks.org

    Two Ways to Check for Palindromes in JavaScript

    This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes [https://www.freecodecamp.com/challenges/check-for-palindromes]”. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. The word “palindrome” was first coined by the English playwright Ben Jonson [https://en.wikipedia.org/wiki/Ben_Jonson] in the 17th

    MARCH 22, 2016 / #JAVASCRIPT

    Two Ways to Check for Palindromes in JavaScript

    Sonya Moisset

    This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.

    A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. The word “palindrome” was first coined by the English playwright Ben Jonson in the 17th century, from the Greek roots palin (“again”) and dromos (“way, direction”). — src. Wikipedia

    In this article, I’m going to explain two approaches, first with built-in functions and second using a for loop.

    Algorithm Challenge

    Return true if the given string is a palindrome. Otherwise, return false.

    A palindrome is a word or sentence that’s spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

    Note. You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.

    We’ll pass strings with varying formats, such as “racecar”, “RaceCar”, and “race CAR” among others.

    function palindrome(str) {

    return true; } palindrome("eye"); ADVERTISEMENT

    Provided test cases

    palindrome(“race car”) should return truepalindrome(“not a palindrome”) should return falsepalindrome(“A man, a plan, a canal. Panama”) should return truepalindrome(“never odd or even”) should return truepalindrome(“nope”) should return falsepalindrome(“almostomla”) should return falsepalindrome(“My age is 0, 0 si ega ym.”) should return truepalindrome(“1 eye for of 1 eye.”) should return falsepalindrome(“0_0 (: /-\ :) 0–0”) should return true

    Which Regular Expression will we need to pass the last test case?

    Regular expressions are patterns used to match character combinations in strings.

    When the search for a match requires something more than a direct match, the pattern includes special characters.

    To pass the last test case, we can use two Regular Expressions:

    /[^A-Za-z0–9]/g or /[\W_]/g

    \W removes all non-alphanumeric characters:\W matches any non-word character\W is equivalent to [^A-Za-z0–9_]\W matches anything that is not enclosed in the brackets

    What does that mean?

    [^A-Z] matches anything that is not enclosed between A and Z

    [^a-z] matches anything that is not enclosed between a and z

    [^0-9] matches anything that is not enclosed between 0 and 9

    [^_] matches anything that does not enclose _

    But in our test case, we need palindrome(“0_0 (: /-\ :) 0–0”) to return true, which means “_(: /-\ :)–” has to be matched.

    We will need to add “_” to pass this specific test case.

    We now have “\W_”

    We will also need to add the g flag for global search.

    We finally have “/[\W_]/g”

    /[\W_]/g was used for pure demonstrative purpose to show how RegExp works. /[^A-Za-z0–9]/g is the easiest RegExp to choose.

    ADVERTISEMENT

    1. Check for Palindromes With Built-In Functions

    For this solution, we will use several methods:

    The toLowerCase() method to return the calling string value converted to lowercase.

    The replace() method to return a new string with some or all matches of a pattern replaced by a replacement. We will use one of the RegExp we just created earlier.

    The split() method splits a String object into an array of strings by separating the string into sub strings.

    The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.

    The join() method joins all elements of an array into a string.

    function palindrome(str) {

    // Step 1. Lowercase the string and use the RegExp to remove unwanted characters from it

    var re = /[\W_]/g; // or var re = /[^A-Za-z0-9]/g;

    var lowRegStr = str.toLowerCase().replace(re, '');

    // str.toLowerCase() = "A man, a plan, a canal. Panama".toLowerCase() = "a man, a plan, a canal. panama"

    // str.replace(/[\W_]/g, '') = "a man, a plan, a canal. panama".replace(/[\W_]/g, '') = "amanaplanacanalpanama"

    // var lowRegStr = "amanaplanacanalpanama";

    // Step 2. Use the same chaining methods with built-in functions from the previous article 'Three Ways to Reverse a String in JavaScript'

    var reverseStr = lowRegStr.split('').reverse().join('');

    // lowRegStr.split('') = "amanaplanacanalpanama".split('') = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]

    // ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].reverse() = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]

    // ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].join('') = "amanaplanacanalpanama"

    स्रोत : www.freecodecamp.org

    Palindrome check in Javascript

    I have the following: function checkPalindrom(palindrom) { for( var i = palindrom.length; i > 0; i-- ) { if( palindrom[i] = palindrom.charAt(palindrom.length)-1 ) { ...

    Palindrome check in Javascript

    Ask Question

    Asked 9 years, 7 months ago

    Modified 1 year ago Viewed 176k times 54

    I have the following:

    function checkPalindrom(palindrom)

    {

    for( var i = palindrom.length; i > 0; i-- )

    {

    if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )

    {

    document.write('the word is palindrome.');

    }else{

    document.write('the word is not palindrome!');

    } } }

    checkPalindrom('wordthatwillbechecked');

    What is wrong with my code? I want to check if the word is a palindrome.

    javascript Share

    Improve this question

    edited Jan 4, 2020 at 3:56

    Bilesh Ganguly 3,3253 3 gold badges 37 37 silver badges 55 55 bronze badges

    asked Feb 11, 2013 at 13:50

    emcee22 1,8035 5 gold badges 23 23 silver badges 32 32 bronze badges 8

    Why do you think there is something wrong with your code? What happens and what do you expect to happen? –

    Felix Kling

    Feb 11, 2013 at 13:58

    2

    From wikipedia: "Allowances may be made for adjustments to capital letters, punctuation, and word dividers". –

    Mojtaba

    Jan 21, 2016 at 18:01

    Add a comment

    43 Answers

    1 2 Next 171

    Maybe I will suggest alternative solution:

    function checkPalindrom (str) {

    return str == str.split('').reverse().join('');

    }

    UPD. Keep in mind however that this is pretty much "cheating" approach, a demonstration of smart usage of language features, but not the most practical algorithm (time O(n), space O(n)). For real life application or coding interview you should definitely use loop solution. The one posted by Jason Sebring in this thread is both simple and efficient (time O(n), space O(1)).

    Share Improve this answer

    edited Mar 14, 2019 at 13:57

    answered Feb 11, 2013 at 14:01

    dfsq 189k24 24 gold badges 232 232 silver badges 252 252 bronze badges 4

    This is clearly the simplest code, although maybe not the most efficient solution. But for someone writing code like the original, perhaps simpler steps toward a good solution are of better help than a leap toward a great solution? –

    Scott Sauyet

    Feb 11, 2013 at 19:02

    3

    You are right. My variant is not teaching OP how to program (there are 5 other great answers more relevant to this original problem), i'm just showing different approach to the problem. And the ability to invent non-obvious ways is also very important. –

    dfsq

    Feb 11, 2013 at 21:01

    5

    you need some extra code in there if the string has spaces or punctuation, fyi –

    Jason

    Aug 13, 2014 at 19:00

    1

    revString("eye") => true while revString("race car") => false while a palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing. How we could improve this? –

    Hamza Bahlaouane

    Sep 1, 2015 at 23:54

    1

    @HamzaBahlaouane The easiest way is to use .toLowerCase (or .toUpperCase) along with a regex that removes the problematic characters, before running the comparision. So, before line 2, add something like str = str.toLowerCase().replace( /[\s~`[email protected]#$%^&*()-_+=[\]{}\\|:;"',<>.?\/\u2000-\u206F\u2E00-\u2E7F\u3000-\u303F]/g, ''); or, if you don't care about Unicode support, str = str.toLowerCase().replace(/\W/g, '') –

    trlkly

    May 5, 2016 at 12:06

    Show 5 more comments

    49

    25x faster than the standard answer

    function isPalindrome(s,i) {

    return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);

    } use like:

    isPalindrome('racecar');

    as it defines "i" itself

    Fiddle: http://jsfiddle.net/namcx0yf/9/

    This is ~25 times faster than the standard answer below.

    function checkPalindrome(str) {

    return str == str.split('').reverse().join('');

    }

    Fiddle: http://jsfiddle.net/t0zfjfab/2/

    View console for performance results.

    Although the solution is difficult to read and maintain, I would recommend understanding it to demonstrate non-branching with recursion and bit shifting to impress your next interviewer.

    explained

    The || and && are used for control flow like "if" "else". If something left of || is true, it just exits with true. If something is false left of || it must continue. If something left of && is false, it exits as false, if something left of a && is true, it must continue. This is considered "non-branching" as it does not need if-else interupts, rather its just evaluated.

    1. Used an initializer not requiring "i" to be defined as an argument. Assigns "i" to itself if defined, otherwise initialize to 0. Always is false so next OR condition is always evaluated.

    (i = i || 0) < 0

    2. Checks if "i" went half way but skips checking middle odd char. Bit shifted here is like division by 2 but to lowest even neighbor division by 2 result. If true then assumes palindrome since its already done. If false evaluates next OR condition.

    i >= s.length >> 1

    3. Compares from beginning char and end char according to "i" eventually to meet as neighbors or neighbor to middle char. If false exits and assumes NOT palindrome. If true continues on to next AND condition.

    स्रोत : stackoverflow.com

    Do you want to see answer or more ?
    Mohammed 15 day ago
    4

    Guys, does anyone know the answer?

    Click For Answer