当前位置:网站首页>Niuke.com: judge whether it is palindrome string

Niuke.com: judge whether it is palindrome string

2022-06-22 19:03:00 lsgoose

There are two ways to solve this problem

Catalog

1. Double pointer

2. Stack ( Flip ) 


1. Double pointer

We can go from two ends to the middle or from the middle to both sides , In a word, we use this symmetrical structure

The code is as follows :

class Solution {
public:
    /**
     *  The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly 
     * 
     * @param str string character string   The string to be judged 
     * @return bool Boolean type 
     */
    bool judge(string str) {
        // write code here
        int left=0;
        int right=str.length()-1;
        while(left<right){
            if(str[left]!=str[right]){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
};

2. Stack ( Flip )

If the idea of stack is to flip the string . Then use this string to check whether it is different from the original string .

The code is as follows :

class Solution {
public:
    /**
     *  The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly 
     * 
     * @param str string character string   The string to be judged 
     * @return bool Boolean type 
     */
    bool judge(string str) {
        // write code here
        string tmp=str;
        reverse(tmp.begin(), tmp.end());
        if(tmp!=str){
            return false;
        }
        return true;
    }
};

原网站

版权声明
本文为[lsgoose]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221729501008.html