459. Repeated Substring Pattern
Problem:
The qualified substring must start from index 0. And its length <= s.length/2. So we find all candidate substrings and test whether they can fit s.
Solution:
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.)Analysis:
The qualified substring must start from index 0. And its length <= s.length/2. So we find all candidate substrings and test whether they can fit s.
Solution:
class Solution { public boolean repeatedSubstringPattern(String s) { if (s == null || s.length() == 0) return false; int len = s.length(); for (int i = len/2; i >= 1; i--) { if (len%i == 0) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < len/i; j++) { sb.append(s.substring(0, i)); } if (s.equals(sb.toString())) return true; } } return false; } }
评论
发表评论