建筑设计网站app,网上营销怎么做,wordpress注册弹出框,上海中小企业服务中心官网题目描述
你会得到一个字符串 text 。你应该把它分成 k 个子字符串 (subtext1, subtext2#xff0c;…#xff0c; subtextk) #xff0c;要求满足:
subtexti 是 非空 字符串 所有子字符串的连接等于 text ( 即subtext1 subtext2 … subtextk text ) 对于所有 i 的有效…题目描述
你会得到一个字符串 text 。你应该把它分成 k 个子字符串 (subtext1, subtext2… subtextk) 要求满足:
subtexti 是 非空 字符串 所有子字符串的连接等于 text ( 即subtext1 subtext2 … subtextk text ) 对于所有 i 的有效值( 即 1 i k ) subtexti subtextk - i 1 均成立 返回k可能最大值。
示例 1
输入text “ghiabcdefhelloadamhelloabcdefghi” 输出7 解释我们可以把字符串拆分成 “(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)”。 示例 2
输入text “merchant” 输出1 解释我们可以把字符串拆分成 “(merchant)”。 示例 3
输入text “antaprezatepzapreanta” 输出11 解释我们可以把字符串拆分成 “(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)”。
提示
1 text.length 1000 text 仅由小写英文字符组成
来源力扣LeetCode 链接https://leetcode.cn/problems/longest-chunked-palindrome-decomposition 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。
分析
定义双指针头指针i指向1尾指针j指向长度-1 因为subString方法算头不算尾 遍历字符串每次遍历截取0i和jlength-1比较是否相等 相等就把他们从字符串剥离结果2继续递归遍历新的字符串直到ij
代码
class Solution {int count0;public int longestDecomposition(String text) {int ltext.length();get(text);return count;}public void get(String text){StringBuffer sb new StringBuffer(text);int lsb.length();int i1;int jl-1;while (ij sb.substring(0,i).equals(sb.substring(j,l))false){i;j--;}if(ij){countcount2;get(sb.substring(i,j));}else if(ij){countcount2;return;}else{countcount1;return;}}
}