Leetcode Valid palindrome C++&python

Source: Internet
Author: User
Tags alphanumeric characters python list

Topic Description Narration

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a Canal:panama" is a palindrome.
"Race a Car" is a palindrome.

Note:
Are you consider that the string might is empty? This was a good question to ask during a interview.

For the purpose of this problem, we define empty string as valid palindrome.

Given a string. Infer whether it is a palindrome string, note: The default empty string in this problem is a palindrome string

Thinking analysis

First, the idea of C + + code is given. Because of the problem of uppercase and lowercase, it is necessary to unify all the letters into lowercase or uppercase. So the transform () method in STL is used here.

The following is a brief record of how transform () is used. The algorithm is used for transformation operations of container elements, such as the following two use prototypes. An iterator interval [first,last] element that runs the Unary Function object op operation. The results of the exchange are placed in the [result,result+ (Last-first)) interval.

There is also an element *i that will be an iterator interval [first1,last1]. *j the element in turn with [first2,first2+ (Last-first)]. Run the two-tuple function operation Binary_op (*I,*J)

Function prototypes

Template<class Inputiterator,class Outputiterator,class Unaryoperator>OutputiteratorTransform (InputiteratorFirst1,InputiteratorLast1,OutputiteratorResultUnaryoperatorOP);Template<class InputIterator1,class InputIterator2, class outputiterator, class binaryoperator > outputiterator                             Transform ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, outputiterator result, binaryoperator 
      
       binary_op )
      ;           

Explanation of the parameters:

Irst1, Last1
Indicates the first iterator interval [first1,last1] for which the element transformation is to take place.
First2
The iterator position that indicates the first element of the second iterator interval to be transformed by the element. The number of elements in the interval is equal to the first interval.

Result
The iterator position that indicates the first element of the iterator interval where the transformed result is stored
Op
Use the Unary Function object op as the number of parameters. The run then returns a result value.

It can be a function or an object within the class overload operator ().
Binary_op
With a two-tuple function object Binary_op as the parameter, a result value is returned after the run. It can be a function or an object within the class overload operator ().

Give a Demo sample code

//Transform algorithm example#include <iostream> //std::cout #include <algorithm> //Std::transform #include <vector> //std::vector #include <functional> /std::p LUs intOp_increase (inti) {return++i; }intMain () {STD:: vector<int>FooSTD:: vector<int>Bar//Set some values:   for(intI=1; i<6; i++) Foo.push_back (i*Ten);//Foo:10Bar.resize (Foo.size ());//Allocate space  STD:: Transform (Foo.begin (), Foo.end (), Bar.begin (), op_increase);//Bar:11  //std::P LUs adds together its arguments:  STD:: Transform (Foo.begin (), Foo.end (), Bar.begin (), Foo.begin (),STD::p lus<int> ());//foo:21, Bayi 101  STD::cout<<"foo contains:"; for(STD:: vector<int>:: Iterator It=foo.begin (); It!=foo.end (); ++it)STD::cout<<"'<< *it;STD::cout<<' \ n ';return 0;}

Output

Foo CONTAINS:21 41 61 81 101

The following descriptive narrative ideas
After unification is converted to uppercase and lowercase, two iterators are used, one pointing to the beginning. A pointer to the end, each time the loop is inferred, assuming that it is not a number or a letter is skipped. Assuming that the contents of the two iterators point to inconsistencies are returned directly, assuming equality then the two iterators go one step at a time. Until two pointers meet, it is inferred that they are palindrome strings.

Give the code implementation:

classsolution{ Public: BOOL Ispalindrome (strings) {transform (S.begin (), S.End(), S.begin (),:: ToLower);string:: Iterator Left=s.begin (), Right=s.End(); while( Left< Right)        {if(!::isalnum (* Left)) Left++;Else if(!::isalnum (* Right)) Right--;Else if((* Left)!=(* Right)) returnfalse;Else{ Left++, Right--;} } returntrue; }};

Note Here the domain operator:: How to use the C + + namespace for the problem. Assuming that there is no domain operator, the error of the function or variable cannot be reported.

Python solution

This problem with the Python list generator and list operations can be very concise solution, the idea is to use the list generator to remove characters other than numbers and letters to get a new string, and then directly infer whether the string and the string is equal in reverse order.

Code implementations such as the following

class Solution:    def isPalindrome(self, s):        forinif i.isalnum()]        return newS==newS[::-1]

Leetcode Valid palindrome C++&amp;python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.