【LeetCode647】迴文子串

思路:採用動態規劃或中心擴展方法都可以,【LeetCode5】已經使用了中心擴展法,這裏採用動態規劃。設置矩陣f,f[i][j]表示字符串中下標從i到j的子串是否爲迴文,獲得f之後,只需要遍歷二維矩陣統計value爲true的元素。動態規劃的公式如下:

 

    public int countSubstrings(String s) {
        if(s==null||s.length()==0) return 0;

        int answer=0;
        int length=s.length();
        boolean[][] f=new boolean[length][length];

        //只計算矩陣的上三角,這個循環的意思是:
        //每一輪i會計算從左上角到右下角的所有數字,j爲橫座標,i+j爲縱座標
        for(int i=0;i<length;i++){
            for(int j=0;i+j<length;j++){
                if(j==i+j) {
                    //對角線肯定爲true
                    f[j][i+j]=true;
                    continue;
                }
                if(s.charAt(j)==s.charAt(i+j)){
                    if(j+1>i+j-1) f[j][i+j]=true;
                    else f[j][i+j]=f[j+1][i+j-1];
                    continue;
                }
                f[j][i+j]=false;
            }
        }

        for(int i=0;i<length;i++){
            for(int j=i;j<length;j++){
                if(f[i][j]) answer++;
            }
        }

        return answer;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章