• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Repeated Substring Pattern

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:
Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"

Output: False
Example 3:
Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

这道题应该没法用DP等解,只能brute force 或者 KMP(为深究)

BruteForce, Best Solution for now except KMP

 1 public boolean repeatedSubstringPattern(String str) {
 2     int l = str.length();
 3     for(int i=l/2;i>=1;i--) {
 4         if(l%i==0) {
 5             int m = l/i;
 6             String subS = str.substring(0,i);
 7             StringBuilder sb = new StringBuilder();
 8             for(int j=0;j<m;j++) {
 9                 sb.append(subS);
10             }
11             if(sb.toString().equals(str)) return true;
12         }
13     }
14     return false;
15 }

 

 

作为Encode String with Shortest Length的subproblem

 1 public class Solution {
 2     public boolean repeatedSubstringPattern(String str) {
 3         int len = str.length();
 4         for (int i=len/2; i>0; i--) {
 5             if (len%i == 0) {
 6                 String substr = str.substring(0, i);
 7                 if (str.replaceAll(substr, "").length() == 0) 
 8                     return true;
 9             }
10         }
11         return false;
12     }
13 }

 

KMP解法未研究,https://discuss.leetcode.com/topic/67590/java-o-n

posted @ 2016-12-13 04:43  neverlandly  阅读(730)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3