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;
        }
  • 相关阅读:
    css中的属性
    css初识和css选择器
    前端html的简单认识
    数据库进阶了解
    数据库索引
    pymysql模块
    数据库的多表查询
    数据库中的行操作
    数据库和表操作以及完整性约束
    数据库概述
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9809346.html
Copyright © 2011-2022 走看看