• 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;
        }
    }
    
    
  • 相关阅读:
    java 显示当前的时间
    java RandomAccessFile 向文件中写入数据,怎么样不覆盖原来的数据
    NCARG 6.2.0 安装方法
    【转】在Fedora 9下用IFC安装MM5
    Linux下GrADS的安装
    我的博客园
    nyist 2 括号配对问题
    nyist 100 1的个数
    进制(堆栈)
    进制
  • 原文地址:https://www.cnblogs.com/linwx/p/7745971.html
Copyright © 2020-2023  润新知