1316. Distinct Echo Substrings

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1316. Distinct Echo Substrings相关的知识,希望对你有一定的参考价值。

Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).

 

Example 1:

Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".

Example 2:

Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".

 

Constraints:

  • 1 <= text.length <= 2000
  • text has only lowercase English letters.
class Solution {
    public int distinctEchoSubstrings(String str) {
        HashSet<String> set = new HashSet<>();
        int n = str.length();
        for (int i = 0; i < n; i++) {
            for (int len = 2; i + len <= n; len += 2) {
                int mid = i + len / 2;
                String subStr1 = str.substring(i, mid);
                String subStr2 = str.substring(mid, i + len);
                if (subStr1.equals(subStr2)) set.add(subStr1);
            }
        }
        return set.size();
    }
}

即使我被逮捕了,我也要高喊一句:“Brute force 无罪!”

class Solution {
    public int distinctEchoSubstrings(String text) {
        Set<String> set = new HashSet();
        for(int i = 0; i < text.length() - 1; i++){
            for(int j = i + 2; j <= text.length(); j+=2){
                if(helper(text.substring(i, j))) 
                set.add(text.substring(i, j));
            }
        }
        return set.size();
    }
    public boolean helper(String s){
        int mid = s.length() / 2;
        return s.substring(0, mid).equals(s.substring(mid));
    }
}

 

以上是关于1316. Distinct Echo Substrings的主要内容,如果未能解决你的问题,请参考以下文章

LC 1316. Distinct Echo Substrings

LeetCode 1316. Distinct Echo Substrings (RK哈希)

Spoj-DISUBSTR - Distinct Substrings~New Distinct Substrings SPOJ - SUBST1~(后缀数组求解子串个数)

SPOJ - SUBST1 D - New Distinct Substrings

SPOJ SUBST1 - New Distinct Substrings(后缀数组[不相同的子串的个数])

SPOJ SUBST1 - New Distinct Substrings(后缀数组[不相同的子串的个数])