How to split a string into as few palindromes as possible?

前端 未结 4 998
时光说笑
时光说笑 2021-02-07 23:57

This is an interview question: \"You\'re given a string, and you want to split it into as few strings as possible such that each string is a palindrome\". (I guess a one char st

4条回答
  •  爱一瞬间的悲伤
    2021-02-08 00:42

    You can do this in O(n^2) time using Rabin-Karp fingerprinting to preprocess the string to find all of the palindromes in O(n^2) time. After the preprocessing, you run code similar to the following:

    np(string s) {
      int a[s.size() + 1];
      a[s.size()] = 0;
      for (int i = s.size() - 1; i >= 0; i--) {
        a[i] = s.size() - i;
        for (int j = i + 1; j <= s.size(); j++) {
          if (is_palindrome(substr(s, i, j))) // test costs O(1) after preprocessing
            a[i] = min(a[i], 1 + a[j]);
      }
      return a[0];
    }
    

提交回复
热议问题