Home > Net >  How to calculate the possible number of sub-string that are palindrome. But substring that are uniqu
How to calculate the possible number of sub-string that are palindrome. But substring that are uniqu

Time:09-01

    template <class T>
    int subPalindrome(T s)
    {
        int res = 0;
        for (int i = 0; i < str.length(); i  )
        {
            for (int j = 0; (j   i) < str.length() && (i - j) >= 0; j  )
            {
                if (str[i   j] != str[i - j])
                {
                    break;
                }
                else res  ;
            }
        }
        for (int i = 0; i < str.length(); i  )
        {
            for (int j = 0; (j   i   1) < str.length() && i - j >= 0; j  )
            {
                if (str[i   j   1] != str[i - j])
                {
                    break;
                }
                else res  ;
    
            }
        }
        return res;
    }

/*I have to write a program that takes a string as input and calculate the possible number of sub-string that are palindrome. But substring that are unique. I have implemented the logic of obtaining the number of all possible substrings but I don't know how to return a count of substrings that are unique

CodePudding user response:

Regarding your questions, a simple solution would be to store the detected palindrome strings into a container that preserve only unique values (e.g., std::set or std::unordered_set), and return it's size.

If you have access to std::unordered_set, it should be faster than std::set. Otherwise, and if performance is an issue, consider adding your string to a std::vector, and call std::sort / std::unique on it at the end. Adding to std::set is O(log(size)). As always, do not try to optimize your code without a good benchmark.

Note :

  • You example could be made simpler by not using a template.
  • As the input string is not modified, consider using a const reference to avoid a copy
  • Also, you could turn the too (very similar) for-loops into functions.
  • Related