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


    分析:
       1.重复字符串的长度肯定会被输入字符串长度整除
       2.遍历可能的重复字符串长度i,从s.length/2开始,不可能大于字符串的一半
       3.如果有个i被输入字符串整除,那么将该(0,i)的字符串合并
       4.与原字符串相比较,如果相等,则为重复字符串。

    实现代码如下:
    class Solution {
        public boolean repeatedSubstringPattern(String s) {
            int len = s.length();
            for(int i = len/2; i>=1;i--){
                if(len%i == 0){
                    int m = len/i;  //代码有m个长度为i的重复字符串
                    String str = s.substring(0, i);  //取出(0,i)的字符串
                    StringBuffer sb = new StringBuffer();
                    for(int j = 0;j < m;j++){
                        sb.append(str);
                    }
                    if(sb.toString().equals(s)){
                        return true;
                    }
                }
            }
            return false;
        }
    }
    
    
  • 相关阅读:
    jQuery的基本使用、实践、效果、API
    关于Nginx那些事儿
    Linux下安装Nginx(保姆教程)
    jQuery的那些事儿
    k8s的应用回滚--record
    MySQL之PXC
    MySQL之高可用MHA
    MySQL之主从半同步复制
    MySQL之MyCat
    MySQL之主从复制
  • 原文地址:https://www.cnblogs.com/linwx/p/7745971.html
Copyright © 2011-2022 走看看