【问题标题】:Count all 4-letter Substring within the given String that matches ignore case a particular String计算给定字符串中与忽略大小写特定字符串匹配的所有 4 字母子字符串
【发布时间】:2022-11-14 05:55:31
【问题描述】:

我需要在 Java 中创建一个程序,在给定的字符串中查找所有出现的 4 字母字符串,在本例中为 "lane"

比较应该不区分大小写,并且在评估子串是否匹配时不应考虑匹配子串的第二个字母。

我当前的代码可以处理某些情况,但在其他情况下,它会返回不正确的出现次数或生成 IndexOutOfBoundsException

我尝试了以下情况:

  1. "Lanee" - 按预期返回 1"Lane" 匹配 "lane")。
  2. "LineLone" - 按预期返回 2"Line" 和“Lone”match“lane”`)。
  3. "LLoenLL" - 产生一个IndexOutOfBoundsException
  4. "enaLLLmnee" - 返回0,但应该是1
  5. "LLONElllneL" - 产生一个IndexOutOfBoundsException

    我的代码:

    public class Stringer {
    
        public Stringer() {}
        
        public int getOccurrences(String s) {
    
            String lower = s.toLowerCase();
            int occurrences = 0;
            int x = 0;
    
            while (x < lower.length()) {
                int traverser = lower.indexOf("l", x);
                if (traverser != -1 && lower.length() > 3) {
                    String sub = lower.substring(x += 2, x += 2);
    
                    if (sub.equals("ne")) {
                        occurrences++;
                    }
                } else {
                    break;
                }
            }
            return occurrences;
        }
    }
    

    我该如何解决这个问题?

【问题讨论】:

  • enaLLLmnee(应该为 1 时返回 0)为什么?另外,您是否也在向后寻找字符串?忽略第二个字母是什么意思?请更新您的问题以解释并提供有关 "works" 含义的更多详细信息。
  • @WJS OP 意味着任何具有三个匹配字符的子字符串,除了第二个,如"LXne",可以被视为与目标字符串"line"的有效匹配。因此,"enaLLLmnee" 包含 1 匹配的子字符串:"Lmne"

标签: java string algorithm


【解决方案1】:

基本上,您需要遍历给定的字符串,检查当前字符是否等于'l' (的第一个字符"lane")。

如果是这种情况,您需要检查当前索引处的 if 字符 +2+3 分别匹配 'n''e'。如果所有这些字符都匹配,则应增加出现次数并将索引推进3 以避免重复检查相同的位置。

笔记循环中的终止条件是i &lt; lower.length() - 3因为目标字符串的长度"lane"4并在检查索引处子字符串的第一个字符时i我们需要能够在索引处的最后一个子字符串字符i + 3

public static int getOccurrences(String s) {
    String lower = s.toLowerCase();
    int occurrences = 0;
    
    for (int i = 0; i < lower.length() - 3; i++) {
        if (lower.charAt(i) == 'l' &&
            lower.charAt(i + 2) == 'n' &&
            lower.charAt(i + 3) == 'e') {

            occurrences++; // incrementing the number of occurrences
            i += 3;        // advancing the index
        }
    }
    return occurrences;
}

main()

public static void main(String[] args) {
    System.out.println(getOccurrences("Lanee"));
    System.out.println(getOccurrences("LineLone"));
    System.out.println(getOccurrences("LLoenLL"));
    System.out.println(getOccurrences("enaLLLmnee"));
    System.out.println(getOccurrences("LLONElllneL"));
}

输出:

1
2
0
1
2

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 2020-06-13
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2016-08-22
    • 2013-11-19
    • 1970-01-01
    相关资源
    最近更新 更多