簡體   English   中英

如何有效地找到最小的正int?

[英]How to find the smallest positive int efficiently?

我正在閱讀文本,我想找到第一個句子的結尾,此時是“。”,“?”或“!”的第一個索引。 在一個字符串中。 所以這是我的Java代碼:

int next = -1;
int nextQ = text.indexOf("? ");
int nextE = text.indexOf("! ");
int nextDot = text.indexOf(". ");
if (nextDot > 0) {
    next = nextDot;
    if (nextQ > 0){
        if (nextQ < next) {next = nextQ;}
        if (nextE > 0) {
            if (nextE < next) {next = nextE;}
        }
    } else if (nextE > 0){
        if (nextE < next) {next = nextE;}
    }
} else if (nextQ > 0){
    next = nextQ;
    if (nextE > 0 && nextE < next){next = nextE;}
} else if (nextE > 0) { next = nextE;}

我相信代碼可以工作,但總共有10個if語句,看起來不太整潔。 我可能想在那里添加更多的句子分隔符,但我不認為這種方法非常靈活。 有沒有更好的方法做同樣的事情? 任何更短的方法來實現相同的結果? ...或者我應該嘗試其他編程語言來解決這類問題? 哪一個?

我建議使用正則表達式一次搜索任何這些分隔符。

String text = <TEXT>;
int next;
Pattern p = Pattern.compile("\\? |! |\\. ");
Matcher m = p.matcher(text);
if (m.find()) {
   int next = m.start();
} else next = -1;

您可以更改正則表達式以精確調整匹配的內容。 例如,我建議在分隔符之后不需要確切的空格,而是需要任何空格字符,這樣換行符或制表符也可以工作。 這將如下: "\\\\?\\\\s|!\\\\s|\\\\.\\\\s" 您可以以類似的方式添加額外的分隔符,並且可以通過一些額外的工作來檢測觸發了哪個分隔符。

Pattern類中的Java正則表達式的文檔在這里這里是一個有用的教程。

使用方法保持干燥:

int firstDelimiterIndex(String s) {
    return minIndex(s.indexOf(". "), minIndex(s.indexOf("? "), s.indexOf("! ")));
}

int minIndex(int a, int b) {
    if (a == -1) return b;
    if (b == -1) return a;
    return Math.min(a, b);
}

或者選擇更快的算法:

for (int i = 0; i < s.length; i++) {
    switch (s.charAt(i)) {
    case '.':
    case '?':
    case '!':
        if (i + 1 < s.length() && s.charAt(i + 1) == ' ') 
            return i;
    }
}

使用Math.min和一個小修改。

首先,將-1轉換為大的正整數:

int largeMinusOne(int a)
{
    return a==-1 ? 9999999 : a;
}

int nextQ = largeMinusOne(text.indexOf("? "));
int nextE = largeMinusOne(...);
int nextDot = largeMinuseOne(...);

現在:

int next = Math.min(Math.min(nextQ, nextE), nextDot);

您可能只想過濾掉不合適的值(== -1)(Java 8):

int nextQ = text.indexOf("? ");
int nextE = text.indexOf("! ");
int nextDot = text.indexOf(". ");
OptionalInt res = IntStream.of(nextQ, nextE, nextDot).filter(i -> i != -1).min();
if (res.isPresent())
    // ok, using res.get()
else
    // none of these substrings found

在現實生活中, 應該是一個笑話,而不是真正的答案。應該使用gandaliter的答案。

我建議只是按字符循環字符串,並在遇到任何這些字符時停止。 你現在正在做的事情效率要低很多倍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM