天天看點

藍橋杯 算法提高 不同單詞個數統計 java集合的使用

不能在集合增強for周遊時移除集合元素,如果有必要,可以使用疊代器iterator
Iterator<String> it = words.iterator();
        while (it.hasNext()) {
            String word = it.next();
            if (check(word,uniques)) {
                // 安全移除集合元素
                it.remove();
            } else {
                uniques.add(word);
            }
        }
           
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

/**
 * <pre>
 *
 算法提高 不同單詞個數統計
 時間限制:1.0s   記憶體限制:512.0MB


 問題描述
   編寫一個程式,輸入一個句子,然後統計出這個句子當中不同的單詞個數。例如:對于句子“one little two little three little bo
 ys”,總共有5個不同的單詞:one, little, two, three, boys。
   說明:(1)由于句子當中包含有空格,是以應該用gets函數來輸入這個句子;(2)輸入的句子當中隻包含英文字元和空格,單詞之間用一
 個空格隔開;(3)不用考慮單詞的大小寫,假設輸入的都是小寫字元;(4)句子長度不超過100個字元。
   輸入格式:輸入隻有一行,即一個英文句子。
   輸出格式:輸出隻有一行,是一個整數,表示句子中不同單詞的個數。
 輸入輸出樣例
 樣例輸入
 one little two little three little boys
 樣例輸出
 5
 *     <pre>
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String[] wordsAarray = line.split(" ");
        ArrayList<String> uniques = new ArrayList<>();
        ArrayList<String> words = new ArrayList<>(Arrays.asList(wordsAarray));

        for (String word : words) {
            if (check(word,uniques)) {
                /*
                 *  這裡本想将已經檢驗過的單詞移出數組,但是這其實是不可行的,
                 *  因為現在在周遊當中.如果有需求,可以使用疊代器iterator
                 */
                // now.remove(word);
            } else {
                uniques.add(word);
            }
        }
        System.out.println(uniques.size());

    }

    private static boolean check(String word, ArrayList<String> arr1) {
        for (String s : arr1) {
            if (word.equals(s)) {
                return true;
            }
        }
        return false;
    }

}