java - 重复从字符串中删除子字符串

标签 java string algorithm replace substring

问题: 从字符串 s 中删除子字符串 t,重复并打印执行相同操作所涉及的步骤数。

解释/工作:

For Example: t = ab, s = aabb. In the first step, we check if t is contained within s. Here, t is contained in the middle i.e. a(ab)b. So, we will remove it and the resultant will be ab and increment the count value by 1. We again check if t is contained within s. Now, t is equal to s i.e. (ab). So, we remove that from s and increment the count. So, since t is no more contained in s, we stop and print the count value, which is 2 in this case.

所以,这是我尝试过的:

  1. 代码 1:

    static int maxMoves(String s, String t) {
        int count = 0,i;
    
        while(true)
        {
            if(s.contains(t))
            {
                i = s.indexOf(t);
                s = s.substring(0,i) + s.substring(i + t.length());
            }
            else break;
    
            ++count;
        }
    
        return count;
    }
    

    由于某种原因,我只能通过 Hackerrank 上的 9/14 测试用例(对于其余的用例,我得到的是“错误答案”)。过了一段时间,我发现Java中有一个叫做replace()的方法。因此,我尝试通过替换 if 条件来使用它,并提出了第二个版本的代码。

  2. 代码 2:

    static int maxMoves(String s, String t) {
        int count = 0,i;
    
        while(true)
        {
            if(s.contains(t))
                s.replace(t,""); //Marked Statement
            else break;
    
            ++count;
        }
    
        return count;
    }
    

    但由于某些原因(我不知道为什么),上面代码中的“标记语句”被无限执行(这是我在替换“标记语句”时注意到的) System.out.println(s.replace(t,""));)。我不明白同样的原因。

因为我只通过了 9/14 测试用例,所以一定有一些逻辑错误导致“错误答案”。如果我使用 代码 1,我该如何克服这个问题?如果我使用代码 2,如何避免无限执行 “标记语句”?或者有人愿意向我推荐 Code 3 吗?

提前谢谢你:)

最佳答案

尝试保存新的(返回的)字符串而不是忽略它。

s = s.replace(t,"");

replace 返回一个新的字符串;您似乎认为它就地改变了给定的字符串。

关于java - 重复从字符串中删除子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46161057/

相关文章:

java - 在 App Engine 上处理图像

c - 如何扫描用户的字数并打印字符串?

c# - 组合框选中的项目到单个字符串

algorithm - 为什么我们做 "implement a queue using 2 stacks"?

java - 即使使用 INNER JOIN FETCH 查询也会出现意外的 JavaAssistLazyInitializer

java - 如何从选定的集合中查找最近的城市

java -> 无法创建监听器 : formatters {[com. puppycrawl.tools.checkstyle.ant.CheckstyleAntTask$Formatter@1326df32

c++ - 将 cout 格式对齐为表格的列

algorithm - 使用 4 个操作找到一对可以达到另一对的整数

python - 在defaultdict中把一个元素放在正确的位置