Check string for palindrome

前端 未结 30 3527
悲哀的现实
悲哀的现实 2020-11-22 02:47

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction.

To check whether a word is a palindrome I get th

30条回答
  •  梦如初夏
    2020-11-22 03:39

    Here my analysis of the @Greg answer: componentsprogramming.com/palindromes


    Sidenote: But, for me it is important to do it in a Generic way. The requirements are that the sequence is bidirectionally iterable and the elements of the sequence are comparables using equality. I don't know how to do it in Java, but, here is a C++ version, I don't know a better way to do it for bidirectional sequences.

    template  
        requires( EqualityComparable< ValueType > ) 
    bool palindrome( I first, I last ) 
    { 
        I m = middle(first, last); 
        auto rfirst = boost::make_reverse_iterator(last); 
        return std::equal(first, m, rfirst); 
    } 
    

    Complexity: linear-time,

    • If I is RandomAccessIterator: floor(n/2) comparissons and floor(n/2)*2 iterations

    • If I is BidirectionalIterator: floor(n/2) comparissons and floor(n/2)*2 iterations plus (3/2)*n iterations to find the middle ( middle function )

    • storage: O(1)

    • No dymamic allocated memory


提交回复
热议问题