Leetcode Valid palindrome C++&python

Source: Internet
Author: User
Tags alphanumeric characters python list

Title Description

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 to determine whether it is a palindrome, note: The default empty string in this problem is a palindrome string

Thinking analysis

First of all, the idea of C + + code, because there are case problems, so we need to unify all the letters to lowercase or uppercase, so this is used in the STL transform () method

The following is a brief description of the use of transform (), the algorithm used for the transformation of container elements, the following two uses the prototype, an iterator interval [first,last] elements, perform unary Function object op operation, the result of the exchange is placed in [result,result+ (Last-first)) interval. The other element of the iterator interval [first1,last1] is *i, followed by the element *j of [first2,first2+ (Last-first)), performing a 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 )
      ;           

Parameter explanation:

Irst1, Last1
Indicates the first iterator interval [first1,last1] for which the element transformation is to take place.
First2
Indicates the iterator position of the first element of the second iterator interval that is to be transformed by the element, and 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
With the Unary Function object op as the argument, the execution returns a result value thereafter. It can be a function or an object within the class overload operator ().
Binary_op
With a two-tuple function object Binary_op as a parameter, execution returns a result value thereafter. It can be a function or an object within the class overload operator ().

Give a 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 describes the idea
Unified to case, the use of two iterators, a point to the beginning, a point to the end, each loop to judge, if not a number or a letter to skip, if the two iterators point to the content of the inconsistency is directly returned, if equal two iterators go one step at a time, until two pointers encounter is a palindrome string

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:: The use of the C + + namespace, if not the domain operator, will not find the function or variable error.

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 determine whether the string and the string is in reverse order is equal.

The code is implemented as follows

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

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode Valid palindrome C++&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.