【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
- [leetcode] 214.Shortest Palindrome
- LeetCode 214. Shortest Palindrome
- leetcode 214. Shortest Palindrome
- LeetCode 214. Shortest Palindrome
- LeetCode 214. Shortest Palindrome
- leetcode.214. Shortest Palindrome
- leetcode-214. Shortest Palindrome
- 【LeetCode】214. Shortest Palindrome
- [LeetCode]214. Shortest Palindrome
- Leetcode 214. Shortest Palindrome
- LeetCode 214. Shortest Palindrome
- LeetCode 214. Shortest Palindrome
- leetcode 214. Shortest Palindrome
- leetcode 214. Shortest Palindrome
- [Leetcode]214. Shortest Palindrome@python
- (Java)LeetCode-214. Shortest Palindrome
- LeetCode hard 214. Shortest Palindrome
- [leetcode] 214. Shortest Palindrome 解题报告
- 套接字编程(1)
- Spring装配bean的三种方式
- 如何设置Session的有效期?
- redis aof 和rdb
- 白话lucene是什么?(一)
- 【LeetCode】214. Shortest Palindrome
- 系统学习深度学习(十四)--权重初始化Xavier
- ARP地址解析协议
- springmvc自定义日期转换器与资源映射mvc:resources 冲突
- ML && DL 知乎问题收集
- iOS常用宏定义
- 网络地址的作用,子网掩码的作用
- crt + xManager 远程打开linux 图形界面
- java.io.IOException: 文件名、目录名或卷标语法不正确。