前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 459. Repeated Substring Pattern

leetcode 459. Repeated Substring Pattern

作者头像
眯眯眼的猫头鹰
发布2019-07-26 15:41:35
3250
发布2019-07-26 15:41:35
举报
文章被收录于专栏:眯眯眼猫头鹰的小树杈

题目要求

代码语言:javascript
复制
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.)

判断一个非空的字符串是否是一个子字符串拼接多次构成的。

思路和代码

直观的思路就是选取所有可能的子字符串,并且将剩余的字符串按照等长截断,将每一段和预期的子字符串进行比较,判断是否相等。代码如下,可以参考注释理解:

代码语言:javascript
复制
    public boolean repeatedSubstringPattern(String s) {
        int length = s.length();
        //i为子字符串长度
        for(int i = length / 2 ; i>=1 ; i--) {
            if(length % i == 0) {
                //重复的次数
                int repeatCount = length / i;
                //假设的重复的子字符串
                String subString = s.substring(0, i);
                int j = 1;
                for( ; j<repeatCount ; j++) {
                    //一旦有一个子字符串不等,就可以退出比较
                    if(!subString.equals(s.substring(j * i, (j + 1) * i))){
                        break;
                    }
                }
                //达到重复次数
                if(j == repeatCount) {
                    return true;
                }
            }
        }
        return false;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档