当前位置:网站首页>Leetcode 30. Concatenate substrings of all words

Leetcode 30. Concatenate substrings of all words

2022-07-06 19:37:00 Java full stack R & D Alliance

The code is as follows :


    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) {
    
        // Dealing with border situations 
        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;
    }

But there is still some abnormal input , Cause code timeout . It's shameless. This kind of input
 Insert picture description here

原网站

版权声明
本文为[Java full stack R & D Alliance]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061133572297.html