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

前端 未结 4 1003
时光说笑
时光说笑 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:45

    bool ispalindrome(string inp)
    {
        if(inp == "" || inp.length() == 1)
        {
            return true;
        }
        string rev = inp;
    
        reverse(rev.begin(), rev.end());
    
        return (rev == inp);
    }
    
    int minsplit_count(string inp)
    {
        if(ispalindrome(inp))
        {
            return 0;
        }
    
        int count= inp.length();
    
        for(int i = 1; i < inp.length(); i++)
        {
            count = min(count, 
                          minsplit_count(inp.substr(0, i))              + 
                          minsplit_count(inp.substr(i, inp.size() - i)) + 
                          1);
        }
    
        return count;
    }
    

提交回复
热议问题