LeetCode T680.Valid Palindrome II/验证回文数

 

 本题思路简单清晰,即判断字符串是否为回文串,若否,则判断其 s[low+1 : high] 与 s[low : high-1] 两个子串是否为回文串,若否则返回非。

我的题解代码如下,leetcode上运行时间20ms,内存占用8.6MB,时间复杂度O(n),空间复杂度O(1).

bool compare(char *s,int low, int high){
    while(low<=high){
        if(s[low]==s[high]){
            low+=1;
            high-=1;
        }
        else return false;
    }
    return true;
}

bool validPalindrome(char * s){
    int len=strlen(s);
    int low=0,high=len-1;
    while(low<=high){
        if(s[low]==s[high]){
            low+=1;
            high-=1;
        }
        else{
            int low1=low+1,low2=low,high1=high,high2=high-1;
            return compare(s,low1,high1) || compare(s,low2,high2);
        }
    }
    return true;
}

 

posted @ 2020-05-19 09:11  runsdeep  阅读(116)  评论(0编辑  收藏  举报