Java構文で検索するには

Java では、文を検索するための各種の検索アルゴリズムを使用できます。一般的な検索アルゴリズムを以下に示します。

  1. 線形探索:文を1つ1つ調べて、目的の文が見つかるかすべての文を調べ終わるまで続ける。最も簡単な探索アルゴリズムだが、効率は悪い。
String[] statements = {"statement1", "statement2", "statement3"};
String targetStatement = "statement2";

for (String statement : statements) {
    if (statement.equals(targetStatement)) {
        System.out.println("Statement found!");
        break;
    }
}
  1. 二分搜索:假设语句已按照特定顺序排序(例如字母顺序),可以通过将目标语句与中间语句进行比较来确定目标语句在前半部分还是后半部分,然后继续在相应的部分中进行搜索。这种算法的效率较高。
String[] statements = {"statement1", "statement2", "statement3", "statement4", "statement5"};
String targetStatement = "statement2";

int low = 0;
int high = statements.length - 1;

while (low <= high) {
    int mid = (low + high) / 2;
    int comparison = targetStatement.compareTo(statements[mid]);

    if (comparison == 0) {
        System.out.println("Statement found!");
        break;
    } else if (comparison < 0) {
        high = mid - 1;
    } else {
        low = mid + 1;
    }
}
  1. 哈希搜索:使用哈希函数将语句映射到唯一的索引位置,然后直接访问该索引位置以查找目标语句。这种算法的效率很高,但需要额外的空间来存储哈希表。
Map<Integer, String> statementMap = new HashMap<>();
statementMap.put(1, "statement1");
statementMap.put(2, "statement2");
statementMap.put(3, "statement3");

String targetStatement = "statement2";

for (Map.Entry<Integer, String> entry : statementMap.entrySet()) {
    if (entry.getValue().equals(targetStatement)) {
        System.out.println("Statement found!");
        break;
    }
}

必要に応じて各種のニーズとデータ構造に基づいて選択され使用できるため、効率の高い文検索が実現できます。

bannerAds