📜  打印字符串所有唯一单词的Java程序

📅  最后修改于: 2022-05-13 01:55:25.133000             🧑  作者: Mango

打印字符串所有唯一单词的Java程序

用于打印字符串存在的所有唯一单词的Java程序。任务是打印字符串仅出现一次的所有单词。

插图:

Input  : Welcome to Geeks for Geeks.
Output : Welcome 
         to
         for
Input  : Java is great.Python is also great.
Output : Java
         Python
         also

方法:

这可以通过以下方式完成:

  1. 使用嵌套循环
  2. 使用地图

天真的方法:使用嵌套循环



这个想法计数字符串中的字符串的发生和打印,如果计数等于1

  1. 使用 split() 方法从字符串提取单词并将它们存储在数组中。
  2. 使用 for 循环遍历单词数组。
  3. 使用另一个循环查找数组中当前单词的出现次数。
  4. 如果找到第二次出现,则增加计数并将单词设置为“”
  5. 如果当前单词的计数等于一个,则打印它

例子:

Java
// Java Program to Print all unique words
// Using nested loops
 
// Main class
public class GFG {
 
    // Method 1
    // To print the unique words
    static void printUniqueWords(String str)
    {
        // Maintaining a count variable
        int count;
 
        // Extract words from string
        // using split() method
        String[] words = str.split("\\W");
 
        // Iteratating over the words array
        for (int i = 0; i < words.length; i++) {
 
            // Setting count of current word to one
            count = 1;
 
            for (int j = i + 1; j < words.length; j++) {
                if (words[i].equalsIgnoreCase(words[j])) {
 
                    // If word found later in array
                    // increment the count variable
                    count++;
 
                    words[j] = "";
                }
            }
 
            // If count of current word is one print it
            if (count == 1 && words[i] != "")
 
                // Print statement
                System.out.println(words[i]);
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "Welcome to geeks for geeks";
 
        // Calling the method 1 to print all unique words
        // in above string passed as argument
        printUniqueWords(str);
    }
}


Java
// Java Program to Print all Unique Words
// Using Map
 
// Importing utility classes from java.util package
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
 
// Main class
public class GFG {
 
    // Method 1
    // To print all unique words in the string
    static void printUniqueWords(String str)
    {
        // Create a new Map ny creating object of HashMap
        // class
        HashMap map
            = new LinkedHashMap();
 
        // Extract words from string
        // using split() method
        String[] words = str.split("\\W");
 
        // Iterating over the words array
        // using for each loop
        for (String word : words) {
 
            // If the word is present in array then
            //
            if (map.containsKey(word)) {
 
                //  Increment its value by one
                // using map.get() method
                map.put(word, map.get(word) + 1);
            }
 
            // Else store the word inside map
            // with value one
            else
                map.put(word, 1);
        }
 
        // Iterate over the map using for each loop
        for (Map.Entry entry :
             map.entrySet()) {
 
            // If value of words equals unity
            if (entry.getValue() == 1)
 
                // Print all those words
                System.out.println(entry.getKey());
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "Welcome to geeks for geeks";
 
        // Calling the Method1 to
        // print all unique words in above string
        printUniqueWords(str);
    }
}



输出
Welcome
to
for

方法二:使用地图



方法:这个想法是使用 Map 来跟踪已经出现的单词。但首先,我们必须从字符串中提取所有单词,因为字符串可能包含许多带有标点符号的句子。

  • 创建一个空地图。
  • 使用 split() 方法从字符串提取单词并将它们存储在数组中。
  • 遍历单词数组。
  • 检查单词是否已经存在于地图中。
  • 如果地图中存在单词,则将其值增加 1。
  • 否则将单词存储为值为 1 的映射内的键。
  • 遍历地图并打印值等于 1 的单词。

例子:

Java

// Java Program to Print all Unique Words
// Using Map
 
// Importing utility classes from java.util package
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
 
// Main class
public class GFG {
 
    // Method 1
    // To print all unique words in the string
    static void printUniqueWords(String str)
    {
        // Create a new Map ny creating object of HashMap
        // class
        HashMap map
            = new LinkedHashMap();
 
        // Extract words from string
        // using split() method
        String[] words = str.split("\\W");
 
        // Iterating over the words array
        // using for each loop
        for (String word : words) {
 
            // If the word is present in array then
            //
            if (map.containsKey(word)) {
 
                //  Increment its value by one
                // using map.get() method
                map.put(word, map.get(word) + 1);
            }
 
            // Else store the word inside map
            // with value one
            else
                map.put(word, 1);
        }
 
        // Iterate over the map using for each loop
        for (Map.Entry entry :
             map.entrySet()) {
 
            // If value of words equals unity
            if (entry.getValue() == 1)
 
                // Print all those words
                System.out.println(entry.getKey());
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "Welcome to geeks for geeks";
 
        // Calling the Method1 to
        // print all unique words in above string
        printUniqueWords(str);
    }
}


输出
Welcome
to
for

注意:时间复杂度为 n 阶,其中空间复杂度为 n 阶。因此,它是最佳方法。