2018-07-02 09:48:48
问题描述:
问题求解:
方法一、问题给了规模n = 2000,也就是说用BF在O(n^2)的时间复杂度可以过,因此,第一个方法就是BF,但是需要注意的是这里已经非常擦边了,所以需要对常数项进行优化。
public int minimumLengthEncoding(String[] words) { boolean[] flag = new boolean[words.length]; int[] lens = new int[words.length]; Arrays.sort(words, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }); int res = 0; for (int i = 0; i < words.length; i++) { lens[i] = words[i].length(); for (int j = i + 1; j < words.length; j++) { int leni = lens[i]; if (lens[j] == 0) lens[j] = words[j].length(); int lenj = lens[j]; if (words[j].substring(lenj - leni).equals(words[i])) { flag[i] = true; break; } } } for (int i = 0; i < words.length; i++) if (!flag[i]) res += words[i].length() + 1; return res; }
方法二、这个方法就比较巧妙了,首先使用Set进行去重,然后对Set中的每个元素将其后缀去除掉,那么最后剩下的就是答案了。
public int minimumLengthEncoding(String[] words) { Set<String> s = new HashSet<>(Arrays.asList(words)); for (String w : words) for (int i = 1; i < w.length(); ++i) s.remove(w.substring(i)); int res = 0; for (String w : s) res += w.length() + 1; return res; }