zoukankan      html  css  js  c++  java
  • 459. 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 

    //Time : O(n), Space: O(1)    
    public boolean repeatedSubstringPattern(String s) {
            if (s == null || s.length() == 0) {
                return true;
            }
            
            int len = s.length();
            
            for (int i = len / 2; i > 0; i--) {//注意:遍历到第二位停止,这样保证sub至少有一位
                if (len % i == 0) {//一定要在能整除的情况下做以下判断
                    int count = len / i;
                    StringBuilder sb = new StringBuilder();
                    String sub = s.substring(0, i);
                    
                    for (int j = 0; j < count; j++) {
                        sb.append(sub);
                    }
                    
                    if (sb.toString().equals(s)) {
                        return true;
                    }
                }
            }
            
            return false;
        }
  • 相关阅读:
    Nacos 1.4.0 集群搭建
    docker mysql5.7
    java设计模式之简单工厂模式
    关于兑现
    Linux用户相关
    centos7开机自启动
    Shell脚本记录日志到文件
    .NetCore常用单元测试框架
    Exchange邮件开发
    Spark——Yarn模式下的日志存储及配置
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9809346.html
Copyright © 2011-2022 走看看