Java | How to remove common word from a string and then concatenate uncommon words?

问题: I was asked in an interview round that you have two Paragraphs P1 = I am Lalit P2 = Lalit Kumar Now find the common word, not the character, then print the uncommon on...

问题:

I was asked in an interview round that you have two Paragraphs

P1 = I am Lalit
P2 = Lalit Kumar

Now find the common word, not the character, then print the uncommon only.

Ex: I am Kumar

What could be the best way to solve this problem?


回答1:

This may be an overkill, but I'd split both strings, collect them into a LinkedHashMap (to retain the original order) and count how many times each string appears, and then filter out the non-unique entries:

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(" "));

回答2:

Try this code:

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));
}

回答3:

You can do something like this...

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++;
            }
        }
    }

So, considering the sizes of the arrays a and b, one can say that this algorithm runs with an efficiency of O(n1 + n2), where we are excluding the sorting time and the time taken to compare the strings.

I hope that you understand the algo. If not, let me know and I can guide you step by step. Cheers!


回答4:

Using ArrayList, below solution should work,

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 listOfAlllWords
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);

  • 发表于 2018-07-10 16:43
  • 阅读 ( 194 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除