测试失败,我在做什么错?

时间:2019-09-28 21:15:54

标签: java arrays arraylist

因此,我一直在尝试让该程序通过两个测试用例。我应该制作一个包含字符的列表,该字符跟随文本中每个非尾部出现的模式。

这是代码...


    public static ArrayList<Character> getCharsThatFollowPattern (String text, String pattern)
    {

        ArrayList<Character> character = new ArrayList<Character>();

        int i = 0;
        while (i <= text.length())
        {
            int index = text.indexOf(pattern, i);
            if (index + pattern.length() < text.length())
            {

                character.add(text.charAt(index + pattern.length()));
            }

            i = i + text.indexOf(pattern, index) + pattern.length();

        }

        return character;
    }

以下是测试案例:

a)为此,我得到[b],但是我应该得到[b,b]

@Test(timeout = 2000)
   public void testGetCharsThatFollowPattern ()
   {
       ArrayList<Character> list = new ArrayList<Character>();
       list.add('b');
       list.add('b');
       ArrayList<Character> chars = PS5Library.getCharsThatFollowPattern("abababa", "aba");
       assertEquals(list, chars);
   }

b)对于这个,我得到[c,d],但我应该得到[c,d,c]

 @Test(timeout = 2000)
    public void testGetCharsThatFollowPattern2 ()
    {
        ArrayList<Character> list = new ArrayList<Character>();
        list.add('c');
        list.add('d');
        list.add('c');
        ArrayList<Character> chars = PS5Library.getCharsThatFollowPattern("abcabdabcab", "ab");
        assertEquals(list, chars);
    }

2 个答案:

答案 0 :(得分:1)

如下更改循环:

h2 = hashlib.md5(targetURL.encode()).hexdigest()
for d in db.rss_crawler.find({"hashedURL":h2}):
    print d

public static ArrayList<Character> getCharsThatFollowPattern (String text, String pattern) { ArrayList<Character> characters = new ArrayList<Character>(); int index = text.indexOf(pattern); while (index >= 0) { if (index + pattern.length() < text.length()) { characters.add(text.charAt(index + pattern.length())); } index = text.indexOf(pattern, index + 1); } return characters; } 将在不再找到该模式时返回index,因此您可以将其用作退出循环的检查。

第二个-1仅执行indexOf(),这是因为您期望+ 1与模式abababa返回aba的重叠。

答案 1 :(得分:0)

问题是您的代码找到了所有单独的事件(通常是所希望的),但是您真正想要的是找到所有所有事件,包括那些重叠的事件。为此,您需要确保在每次迭代中只移动一个字符,而不要移动匹配长度。

public static ArrayList<Character> getCharsThatFollowPattern (String text, String pattern) {
    List<Character> characters = new ArrayList<>();
    for (int i = 0; i < text.length(); i++) {
        i = text.indexOf(pattern, i);
        if (i < 0) break;

        int charIndex = i + pattern.length();
        if (charIndex >= text.length()) break;
        characters.add(text.charAt(charIndex));
    }
    return characters;
}