码迷,mamicode.com
首页 > 其他好文 > 详细

CareerCup Facebook Total number of substring palindrome

时间:2014-06-21 23:59:42      阅读:422      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

Write a function for retrieving the total number of substring palindromes. 
For example the input is ‘abba‘ then the possible palindromes= a, b, b, a, bb, abba 
So the result is 6. 

Updated at 11/11/2013: 

After the interview I got know that the O(n^3) solution is not enough to go to the next round. It would have been better to know before starting implementing the solution unnecessarily ...


------------------------------------------------------------------------


Similar to leetcode Longest Palindromic Substring Part II in my blog, the code is like:

#include <iostream>
#include <map>
#include <algorithm>
#include <limits.h>
#include <assert.h>
#include <string.h>
#include <vector>
using namespace std;
string preprocess(string s) {
  string res = "^#";
  for (int i = 0; i < s.length(); ++i) {
    res += s[i];
    res += '#';
  }
  res += '$';
  return res;
}
int getPalindromeNum(string s) {
  string str = preprocess(s);
  int i, j, len = str.length(), C = 0, R = 0, res = 0, ii;

  vector<int> T(len + 1, 0), P(len + 1, 0);

  for (i = 1; i < len; ++i) {
    ii = 2*C - i;
    P[i] = (R - i) > 0 ? min(P[ii], R-i) : 0;
    //bug1: P[i] = (R - i) > 0 ? P[i] : 0
    while (str[i + P[i] + 1] == str[i - P[i] - 1])
      ++P[i];
    res += (P[i] + 1) / 2;
    //bug2: res += P[i]; 
    if (i + P[i] > R) {
      C = i;
      R = i + P[i];
    }
  }
  return res;
}
int main() {
  //string s = "abcba";
  string s = "aaaaa";
  
  int res = getPalindromeNum(s);
  return 0;
}


CareerCup Facebook Total number of substring palindrome,布布扣,bubuko.com

CareerCup Facebook Total number of substring palindrome

标签:style   class   blog   code   http   tar   

原文地址:http://blog.csdn.net/taoqick/article/details/32188659

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!