Leetcode 30. 串联所有单词的子串
Posted Java全栈研发大联盟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 30. 串联所有单词的子串相关的知识,希望对你有一定的参考价值。
代码如下:
public static List<Integer> findSubstring(String s, String[] words)
List<Integer> result = new ArrayList<>();
int length = 0;
for (String word : words)
length += word.length();
for (int i = 0; i <= s.length() - length; i++)
String substring = s.substring(i, i + length);
boolean tran = tran(substring, words);
if (tran)
result.add(i);
return result;
public static boolean tran(String str, String[] words)
//处理边界情况
if (words.length == 1)
return str.equals(words[0]);
boolean result = false;
for (int i = 0; i < words.length; i++)
if (str.startsWith(words[i]))
StringBuilder stringBuilder = new StringBuilder(str);
String substring = stringBuilder.delete(0, words[i].length()).toString();
String[] restWords = subWords(words, i);
if (tran(substring, restWords))
result = true;
return result;
public static String[] subWords(String[] words, int i)
String[] strings = Arrays.copyOf(words, words.length);
for (int k = i; k < strings.length - 1; k++)
strings[k] = strings[k + 1];
strings = Arrays.copyOfRange(strings, 0, strings.length - 1);
return strings;
但是还是有一部分变态的输入情况,导致代码超时。 太无耻了这种输入情况
以上是关于Leetcode 30. 串联所有单词的子串的主要内容,如果未能解决你的问题,请参考以下文章
算法leetcode|30. 串联所有单词的子串(rust重拳出击)