【LeetCode】214. Shortest Palindrome

来源:互联网 发布:农村淘宝有发展前景 编辑:程序博客网 时间:2024/05/28 05:19

先贴一个C语言版的,没有通过AC。自我感觉良好,没有bug,但是在最后一个测试用例上超出运行时间。等待装好开发环境后,测试一下。

char* shortestPalindrome(char* s) {    char c;    int i = 1;    char* length =NULL;char* copyStart = NULL;char* copyEnd =NULL ;char* sEnd = NULL;char* temp = NULL;    bool notSure = true,notSureP = true,notSureL = true;    if(strlen(s)<2 && !s ){        return s;    }    //逆序判断最大回文串    for(i=strlen(s)/2;i>0;i--){        length = s + i-1;        notSure = true,notSureP = true,notSureL = true;        copyStart = length+1;//取前个长度后,再截取length个长度;        do{            if(notSureP && (*length) != (*copyStart)){                notSureP = false;            }            if(notSureL && (*length) != *(copyStart+1)){                notSureL = false;            }            notSure = notSureP||notSureL;            length--;            copyStart++;        }while(length!=s && notSure);        if(notSure){           copyEnd = notSureL?s+i*2+1:s+i*2;             break;        }    };    //补足待返回字符串后面的子串    if(!copyEnd){       copyEnd = s+1;    }    sEnd = s+strlen(s)-1;    temp = sEnd+1;    while(copyEnd!=sEnd+1){        *(temp) = *(copyEnd);        temp++;        copyEnd++;    }    *temp = '\0';    //反转前部分字符串    copyStart = s;// s = aacecaaaa    while((sEnd != copyStart) && (sEnd != copyStart+1)){        c = *sEnd;        *sEnd = *copyStart;        *copyStart = c;        copyStart ++;        sEnd --;    };    c = *sEnd;    *sEnd = *copyStart;    *copyStart = c;    return s;}

贴个JS版的,通过AC.

var shortestPalindrome = function(s) {    var hasP =1;    var preStr = "";    for(i=1;i<=s.length/2;i++){        preStr = s.charAt(i-1)+preStr;        if(preStr == s.substr(i+1,i)){            hasP = 2*i+1;        }else if(preStr == s.substr(i,i)){            hasP = 2*i;        }    }    return s.substr(hasP).split("").reverse().join("") + s;};
0 0
原创粉丝点击