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;
        }
    }
    
    
  • 相关阅读:
    Node.js 安装配置
    ITerm2配置-让你的mac命令行更加丰富高效
    ECharts 图表工具
    Vue 安装
    element-ui 安装
    mysql高级查询
    数据库第三章 参考
    DML和DQL 总结
    数据库第二章 参考答案
    数据库编程技术 第一章
  • 原文地址:https://www.cnblogs.com/linwx/p/7745971.html
Copyright © 2011-2022 走看看