最大长度回文子串(Manacher's algorithm)

输出最大长度的回文子串。

 1 string longestPalindrome(string s)
 2 {
 3 
 4 
 5     int id, mx, i, j, len, maxlen;
 6     vector<char> cvec;
 7     vector<int> ivec;
 8     string str;
 9     int ma, k;
10 
11     id = 0;
12     mx = 0;
13     ivec.push_back(1);
14     len = s.size();
15     maxlen = 2*s.size() + 1;
16 
17     for (i = 0; i < len; ++i)
18     {
19         cvec.push_back('#');
20         cvec.push_back(s[i]);
21     }
22     cvec.push_back('#');
23 
24 
25     for (i = 1; i < maxlen; ++i)
26     {
27         if (mx > i)
28         {
29             int temp;
30             temp = ((mx - i - 1) > (ivec[2*id - i])) ? (ivec[2*id - i]) : (mx - i - 1);
31             ivec.push_back(temp);
32         }
33         else
34             ivec.push_back(1); 
35 
36         for (; (i - ivec[i] >= 0) && ((i + ivec[i]) < maxlen) && (cvec[i-ivec[i]] == cvec[i+ivec[i]]); ++ivec[i])
37             ;
38 
39         if (mx < ivec[i] + i -1 )
40         {
41             mx = ivec[i] + i - 1;
42             id = i;
43         }
44     }
45 
46     ma = 0;
47     for (i = 0; i < maxlen; ++i)
48     {
49         if (ivec[i] > ma)
50         {
51             ma = ivec[i];
52             k = i;
53         }
54     }
55 
56     for (j = 0, i = k - ivec[k] + 1; j < ivec[k] - 1; ++i, ++j)
57     {
58         ++i;
59         str.push_back(cvec[i]);
60     }
61     
62     return str;
63 }

 对于判断一个整数是否是回文,有另外的方法,不需要另外开辟空间。把地位当做高位,计算其值。

比如:123,计算3*100 + 2*10 + 1 的值是否与123相等。代码如下:

 1 void isPalindrome(int integer)
 2 {
 3     int temp, count, num, digit;
 4 
 5     if (integer < 0)
 6     {
 7         printf("不是回文整数\n");
 8         return;
 9     }
10     if (integer == 0)
11     {
12         printf("是回文整数\n");
13         return;
14     }
15 
16     temp = integer;
17     count = 0;
18     while (temp)
19     {
20         count++;
21         temp = temp / 10;
22     }
23 
24     temp = integer;
25     num = 0;
26     while (temp > 0)
27     {
28         digit = temp - (temp / 10) * 10;
29         num = digit * int_pow(count) + num;
30         temp = temp / 10;
31         count--;
32     }
33 
34     if (num == integer)
35     {
36         printf("是回文整数\n");
37     }
38     else
39     {
40         printf("不是回文整数\n");
41     }
42 
43 }
44 
45 int int_pow(int x)
46 {
47     int result = 1;
48 
49     while (x > 1)
50     {
51         result = result * 10;
52         x--;
53     }
54     return result;
55 }

 

posted @ 2014-10-21 10:17  yyxayz  阅读(247)  评论(0编辑  收藏  举报