标签:xpl cte i++ example hash nbsp lis ext for
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
标签:xpl cte i++ example hash nbsp lis ext for
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12345050.html