【Lintcode】1856. Sub-palindrome

题目地址:

https://www.lintcode.com/problem/sub-palindrome/description

给定一个字符串 s s s,求其有多少个不同的回文子串。

直接枚举中心,然后枚举所有以当前位置为中心的回文串,加入一个哈希表中,最后返回哈希表的size即可。代码如下:

import java.util.HashSet;
import java.util.Set;

public class Solution {
    /**
     * @param s: the string
     * @return: the number of substring
     */
    public int countSubstrings(String s) {
        // Write your code here.
        Set<String> set = new HashSet<>();
        // 枚举左端点
        for (int i = 0; i < s.length(); i++) {
            int l = i;
            // 枚举右端点
            for (int j = 0; j < 2; j++) {
                int r = l + j;
                while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
                    set.add(s.substring(l, r + 1));
                    l--;
                    r++;
                }
                
                // 最后要把左端点恢复原状
                l = i;
            }
        }
        
        return set.size();
    }
}

时间复杂度 O ( l s 2 ) O(l_s^2) O(ls2),空间 O ( l s 3 ) O(l_s^3) O(ls3)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值