首页 > 其他 > 详细

leetcode-Valid Palindrome

时间:2015-04-02 18:35:36      阅读:238      评论:0      收藏:0      [点我收藏+]
 1 bool isPalindrome(string s) {
 2     int start=0, end=s.length()-1;
 3     while(start<end) {
 4         if (!isalnum(s[start])) start++;
 5         else if (!isalnum(s[end])) end--;
 6         else {
 7             if (tolower(s[start++])!=tolower(s[end--])) return false;
 8         }
 9     }
10     return true;
11 }

上面为他人的代码,简洁美

我的代码不够简洁,想法先遍历一遍,得到s中数字和字符的个数,同时把它们存到新数组中,对新数组遍历一半,用栈的思想来判断。

技术分享
 1 class Solution {
 2 public:
 3     bool isPalindrome(string s) {
 4         int strlength,mid,top,next;
 5         char*p=NULL;
 6         char*stack=NULL;
 7         p=(char *)malloc((1+s.size()*sizeof(char)));
 8         
 9        // char*stack=NULL;
10         //stack=(char *)=malloc((1+s.size()*sizeof(char));
11         
12         top=0;   
13         if(s.empty())
14         {
15             return true;
16         }
17         else{
18         for(int i=0;i<s.size();i++)
19         {
20            // int j=0;
21             if(isalnum(s[i]))
22             {
23                 strlength++;
24                 p[strlength]=s[i];
25             }
26                 
27         }
28         //stack=(char *)malloc((1+strlength)*sizeof(char)));
29         stack=(char *)malloc((1+strlength)*sizeof(char));
30         mid=strlength/2;
31         if(strlength%2==0)
32         {
33             next=mid+1;
34         }
35         else
36         {
37             next=mid+2;
38         }
39         for(int i=1;i<=mid;i++)
40         {
41             stack[++top]=p[i];
42         }
43         for(int i=next;i<=strlength;i++)
44         {
45             if(p[i]==stack[top]||p[i]==stack[top]+32||p[i]==stack[top]-32)
46             {
47                 top--;
48             }
49             else
50                 return false;
51         }
52         if(top==0)
53         {
54             return true;
55         }
56         else return false;
57     }
58     }
59 };
View Code

 

leetcode-Valid Palindrome

原文:http://www.cnblogs.com/quanchou/p/4387444.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!