Find all substrings that are palindromes

后端 未结 9 694
伪装坚强ぢ
伪装坚强ぢ 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 21:50

    I tried the following code and its working well for the cases Also it handles individual characters too

    Few of the cases which passed:

    abaaa --> [aba, aaa, b, a, aa] 
    geek  --> [g, e, ee, k] 
    abbaca --> [b, c, a, abba, bb, aca] 
    abaaba -->[aba, b, abaaba, a, baab, aa] 
    abababa -->[aba, babab, b, a, ababa, abababa, bab] 
    forgeeksskeegfor --> [f, g, e, ee, s, r, eksske, geeksskeeg, 
                          o, eeksskee, ss, k, kssk]
    

    Code

    static Set set = new HashSet(); 
    static String DIV = "|";
    
    public static void main(String[] args) {
        String str = "abababa";
        String ext = getExtendedString(str);
    
        // will check for even length palindromes
        for(int i=2; i ext.length()-1) {
            return;
        }
        if (ext.charAt(mid-offset) == ext.charAt(mid+offset)) {
            set.add(ext.substring(mid-offset, mid+offset+1).replace(DIV, ""));
            addPalindromes(mid, offset+2, ext);
        }
    }
    

    Hope its fine

提交回复
热议问题