Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Best way to do Palindrome 2 challenge
    I'm practicing the challenge in C++, so would you recommend stripping all the punctuation away from the string first, or just skip over them when reading the string? Link to challenge: Palindrome 2
    kittycoder posted this question on 12/16/13 | cpp, palindrome, challenge, punctuation
    Answers
  • +
  • 4
  • -
  • In C++ you can strip non-alphanumeric characters from a string using a function predicate and some algorithms, in several different ways. First the function predicate:
    bool notalnum(char c)
    {
      return !std::isalnum(c);
    }
    
    1. The erase remove idiom, operates on an existing string.
    str.erase(std::remove_if(str.begin(),str.end(),notalnum),str.end());
    2. remove_copy_if, creates a new string from an existing string using a predicate.
    string s2;
    std::remove_copy_if(str.begin(), str.end(), std::back_inserter(s2), notalnum);
    3. Many others, including classic for loop, but the above two methods have become favorable to me. You can also substitute the use of a function predicate with
    std::not1(std::ptr_fun(::isalnum))
    You can convert all letters in a string to lowercase or uppercase using std::transform.
    std::transform(str.begin(), str.end(), str.begin(), ::toupper);
    Naturally all of these sub-problems can be found by searching the web. Now challenge yourself and solve this problem without using any loops. There are several ways to do it. Good luck!
  • +
  • 1
  • -
  • Another useful option is to simply use regexp to alter what you need. For example my Ruby code:
    def PalindromeTwo(str)
      str = str.gsub(/[^a-zA-Z]/, '').downcase
      if str == str.reverse then str = true else str = false end
      return str   
    end
    
  • +
  • 0
  • -
  • Try to use this:
    if(isalpha(str[i]))
    {
    // do sth to skip all spaces and punctuation, symbol
    //use tolower() to the elements in string
    }
    //then do the same thing a in Palindrome 1 to achieve the result.
    
    Log in to write an answer.