要求:2个英文字符串中,取相同的大于等于4个字母的词组
比如:
字符串1:" xingMeiLingabcdef WorldHello",字符串2:"mnjqlup WorldLingLing xingMeiLingHello"获取交接:[xingMeiLing, Hello, World]
实现方式:递归
// 前提是对比两个文本的长短,参数1,是短的; 参数2,是长的
private static Set<String> getNewWords(String shortWord, String longWord){Set<String> result = new HashSet<>();while (shortWord.length()>=5) {String wordFirst = shortWord.substring(0,4);if(longWord.contains(wordFirst)){for (int i = 4; i < shortWord.length() ; i++) {if (longWord.contains(wordFirst+shortWord.charAt(i))){wordFirst = wordFirst+shortWord.charAt(i);}else {break;}}result.add(wordFirst);shortWord =shortWord.substring(wordFirst.length());getNewWords(shortWord,longWord);}else {shortWord =shortWord.substring(1);}}return result;
}
闲言碎语: 递归比较适合数据量不大的,毕竟它比较占内存