Leetcode 30. 串联所有单词的子串

少年击剑更吹箫,剑气箫心一例消。这篇文章主要讲述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. 串联所有单词的子串】


    推荐阅读