找出数组中的第一个回文字符串

题目 找出数组中的第一个回文字符串

image-50d8dfc4

思路分析

本来想用异或做

如果是回文串的话 相同的数抵消 若偶数长 最后得0 若奇数长 最后得剩余的那个数 与中间数比较相等

但是有可能存在巧合 一堆不同的数异或后得到的结果 正好等于中间的数……

所以这样不行

image-52ea3635

代码写了蛮久的 别浪费了 贴在这

class Solution {

public:

    bool check(string &word){

        int l=0,r=word.size()-1;

        while(l<r){

            if(word[l]!=word[r])

                return false;

            l++,r--;

        }

        return true;

    }

    string firstPalindrome(vector<string>& words) {

        for(auto word:words){

            if(check(word))

                return word;

        }

        return "";

    }

};

那老老实实做吧

左右指针中间逼近 若发现有一位不等就判否 下一个

代码实现

class Solution {

public:

    bool check(string &word){

        int l=0,r=word.size()-1;

        while(l<r){

            if(word[l]!=word[r])

                return false;

            l++,r--;

        }

        return true;

    }

    string firstPalindrome(vector<string>& words) {

        for(auto word:words){

            if(check(word))

                return word;

        }

        return "";

    }

};

同类题型

视频讲解


⬅️ 对撞指针 🏠 00-刷题理模型 ➡️ 接雨水