Repeated Substring Paterm
来源:互联网 发布:一物降一物 知乎 编辑:程序博客网 时间:2024/06/10 13:35
题目描述:
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: TrueExplanation: It's the substring "ab" twice.
Example 2:
Input: "aba"Output: False
Example 3:
Input: "abcabcabcabc"Output: TrueExplanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
原题地址:
https://leetcode.com/problems/repeated-substring-pattern/#/description
刷题杂感:
刷这道题的过程还是一如既往:很快想到第一种做法,然后因为时间复杂度的原因扑街了,然后又尝试了另一种更“简洁”一点的算法
/* == 我这样的菜鸡能想出来的最简洁的做法了orz*/
刷题越多,越觉得做题的时候要多想想再码代码,得出正确的结果固然很棒,但是想出一个时间/空间复杂度较小的算法更重要。
LeetCode的题目和Lintcode相比,难度可能相差不大,但是LeetCode的测试要求更高,所有代码经常扑街orz。还有就是英文Description有时候看不懂,必须配合着example一起看才能理解题意[谁让我这个菜鸡预备程序员英语姿势水平不高呢]
共勉吧!希望能有一天可以徒手写代码,肉眼debug!
第一种做法:
public boolean repeatedSubstringPattern(String s) { boolean b = false; for(int i =1;i<=s.length()/2;i++){ //遍历所有可能性 String ele = s.substring(0,i); //子基字符串 int number = s.length()/ele.length(); if(getNewString(ele,number).equals(s)){ //判断根据子字符串得出的新字符串是否和原字符串相等 b = true; break; } } return b; } public String getNewString(String s,int m){ String str = ""; for(int i =0;i<m;i++){ str = s+str; } return str; }
升级版的做法;
public boolean repeatedSubstringPattern(String s) { boolean b = false; int length = 1; int i = length; while(i+length<=s.length()){ String str = s.substring(0,length); //确定基字符串 if(s.substring(i,length+i).equals(str)){ //判断该字符串是否为真-基字符串 if(s.length()%length==0){ //如果基字符串能整除原字符串,则为真 b = true; } i = i+length; }else{ b = false; length++; i = length; } } return b; }
阅读全文
0 0
- Repeated Substring Paterm
- Longest Repeated Substring
- Longest Repeated Substring zoj3199
- Longest Repeated Substring
- 459. Repeated Substring Pattern
- 459. Repeated Substring Pattern
- Repeated Substring Pattern
- 459. Repeated Substring Pattern*
- 459. Repeated Substring Pattern
- Repeated Substring Pattern
- 459. Repeated Substring Pattern
- 459. Repeated Substring Pattern
- 459. Repeated Substring Pattern
- Repeated Substring Pattern
- Leetcode Repeated Substring Pattern
- 459. Repeated Substring Pattern
- LEETCODE--Repeated Substring Pattern
- 459. Repeated Substring Pattern
- java数据类型的默认值
- LeetCode
- 《机器学习实战》学习笔记
- Golang学习笔记 包和项目构成
- 抢占式短作业优先调度算法(SJF)
- Repeated Substring Paterm
- 复数类的运算
- 最近要做的
- Moving Tables HDU 1050
- python爬取天气数据
- 手动安装jenkins默认插件
- C++/MFC-多线程绘图
- 对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。 给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。
- Spring(一)--控制反转