首页 > 其他 > 详细

1316. Distinct Echo Substrings

时间:2020-02-22 13:56:32      阅读:61      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/wentiliangkaihua/p/12345050.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!