Find all substrings that are palindromes

后端 未结 9 686
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 21:28

If the input is \'abba\' then the possible palindromes are a, b, b, a, bb, abba.
I understand that determining if string is palindrome is easy. It would be like:

9条回答
  •  情话喂你
    2020-12-07 22:02

    Perhaps you could iterate across potential middle character (odd length palindromes) and middle points between characters (even length palindromes) and extend each until you cannot get any further (next left and right characters don't match).

    That would save a lot of computation when there are no many palidromes in the string. In such case the cost would be O(n) for sparse palidrome strings.

    For palindrome dense inputs it would be O(n^2) as each position cannot be extended more than the length of the array / 2. Obviously this is even less towards the ends of the array.

      public Set palindromes(final String input) {
    
         final Set result = new HashSet<>();
    
         for (int i = 0; i < input.length(); i++) {
             // expanding even length palindromes:
             expandPalindromes(result,input,i,i+1);
             // expanding odd length palindromes:
             expandPalindromes(result,input,i,i);
         } 
         return result;
      }
    
      public void expandPalindromes(final Set result, final String s, int i, int j) {
          while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) {
                result.add(s.substring(i,j+1));
                i--; j++;
          }
      }
    

提交回复
热议问题