Loading...

【中心扩展法】LCR_020_回文子串

在这里插入图片描述

求解代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
        public int countSubstrings(String s) {

            if(s==null||s.length()==0){
                return 0;
            }

            int ans = 0;

            for(int i=0;i<s.length();i++){
            		 // 1. 以i为中心(奇数长度回文)
                ans += countPalindrome(s, i, i);
                // 2. 以i和i+1为中心(偶数长度回文)
                ans += countPalindrome(s, i, i+1);
            }
            return ans;
        }

        private int countPalindrome(String s,int left,int right) {
            int count = 0;

            while(left>=0&& right< s.length()&&s.charAt(left)==s.charAt(right)){
                count++;
                left--;
                right++;
            }

            return count;
        }
最后更新于 2026-04-05 17:35:33
Code Road Record