zoukankan      html  css  js  c++  java
  • 【LeetCode】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 times. (And the substring "abcabc" twice.)

    题意:

    查看一个字符串是否可以由子字符串重复组成,可以的话返回真,否则返回假

    思路:

    改变扫描步长,二重循环

    1.假定长度为p的字符串可以重复组成,1=<p<=len(s)

    2.重复多次循环,每个循环中不断验证str[i]!=str[i+p],如果为真,break;

    3.如果有一次可以扫描到结尾,也就是i+p=l,而且i%p==0,那么返回真

     1 bool repeatedSubstringPattern(char* str) {
     2     int p,i;
     3     int l=strlen(str);
     4     int flag=0;
     5     for(p=1;p<=l/2;p++)
     6     {
     7         for(i=0;i<l-p;i++)
     8         {
     9             flag=0;
    10             if(str[i]!=str[i+p])
    11                 {
    12                     flag=1;
    13                     break;
    14                 }
    15         }
    16         if(0==flag&&i%p==0)
    17             return true;
    18     }
    19     return false;
    20 }

    这种解法的时间复杂度为O(n^2),还有一种利用KMP算法的,时间复杂度为O(n),我还没做,待补充

  • 相关阅读:
    Python 字符串操作
    Python 字典操作
    16 飞机大战:思路整理、重要代码
    15 飞机大战:pygame入门、python基础串连
    14 windows下安装pygame模块
    13 制作模块压缩包、安装模块
    12 包及导包
    11 模块、模块的搜索顺序、__file__内置属性、__name__属性
    异常集
    10 异常
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6158693.html
Copyright © 2011-2022 走看看