码迷,mamicode.com
首页 > 其他好文 > 详细

1316. Distinct Echo Substrings

时间:2020-02-22 14:02:12      阅读:83      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!