爪哇 |如何从字符串中删除常用单词,然后连接不常见的单词?



我在一轮面试中被问到你有两个段落

P1 = I am Lalit
P2 = Lalit Kumar

现在找到常用词,而不是字符,然后只打印不常用的。

Ex: I am Kumar

解决这个问题的最佳方法是什么?

这可能是矫枉过正,但我会拆分两个字符串,将它们收集到一个LinkedHashMap(以保留原始顺序(并计算每个字符串出现的次数,然后过滤掉非唯一条目:

String p1 = "I am Lalit";
String p2 = "Lalit Kumar";
String result =
Stream.concat(Arrays.stream(p1.split("\s")), Arrays.stream(p2.split("\s")))
.collect(Collectors.groupingBy(Function.identity(), 
LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.joining(" "));

试试这段代码:

public static void main(String[] args) {
String str1 = "I am Lalit";
String str2 = "Lalit Kumar";
List<String> set1 = new ArrayList<>(Arrays.asList(str1.split(" ")));
for (String s : Arrays.asList(str2.split(" "))) {
if (set1.contains(s)) set1.remove(s);
else set1.add(s);
}
System.out.println(String.join(" ", set1));
}

你可以做这样的事情...

public static void printUncommon(String s1, String s2) {
String[] a = s1.split(" ");
String[] b = s2.split(" ");
Arrays.sort(a);
Arrays.sort(b);
int n1 = a.length;
int n2 = b.length;
int i = 0;
int j = 0;
while(i < n1 && j < n2) {
int compare = a[i].compareToIgnoreCase(b[j]);
if(compare == 0) {
i++;
j++;
}
else if(compare < 0) {
System.out.println(a[i]);
i++;
}
else if(compare > 0) {
System.out.println(b[j]);
j++;
}
}
if(i == n1) {
while(j < n2) {
System.out.println(b[j]);
j++;
}
}
else if(j == n2) {
while(i < n1) {
System.out.println(a[i]);
i++;
}
}
}

因此,考虑到数组的大小ab,可以说该算法以 O(n1 + n2( 的效率运行,其中我们排除了排序时间和比较字符串所需的时间。

我希望你理解算法。如果没有,请告诉我,我可以逐步指导您。干杯!

使用 ArrayList,下面的解决方案应该可以工作,

String p1 = "I am Lalit";
String p2 = "Lalit Kumar";
List p2_wordList = Arrays.asList(p2.split(" ")); // create List reference
List<String> listOfAlllWords = new ArrayList<String>(Arrays.asList(p1.split(" "))); // create a new ArrayList Object for all words in p1
listOfAlllWords.addAll(p2_wordList); // add all words from p2
System.out.println(listOfAlllWords); // output-> [I, am, Lalit, Lalit,Kumar]
List<String> listOfCommonWords = new ArrayList<String>(Arrays.asList(p1.split(" "))); // create a new ArrayList Object for all word in p1 one more time
listOfCommonWords.retainAll(p2_wordList); // retain only common words from p1 and p2
System.out.println(listOfCommonWords); // output--> [Lalit]
listOfAlllWords.removeAll(listOfCommonWords); // remove above common words from istOfAlllWords
System.out.println(listOfAlllWords); // output--> [I, am, Kumar]
StringBuffer sb = new StringBuffer(); // for final output
Iterator<String> itr = listOfAlllWords.iterator();
while (itr.hasNext()) {
sb.append(itr.next() + " ");
}
System.out.println(sb);

最新更新