gpt4 book ai didi

java - codingBat plusOut 使用正则表达式

转载 作者:行者123 更新时间:2023-11-30 11:59:23 25 4
gpt4 key购买 nike

这类似于我之前的努力(wordEndsrepeatEnd):作为一种脑力练习,我想仅使用正则表达式来解决这个玩具问题。

Description from codingbat.com :

Given a string and a non-empty word string, return a version of the original string where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

没有提及是否允许重叠(例如什么是 plusOut("+xAxAx+", "xAx")?),但我的非正则表达式解决方案不处理重叠和它通过了,所以我想我们可以假设 word 不重叠出现,如果它使它更简单的话(如果您为两种变体提供解决方案,则加分!)。

无论如何,我想使用正则表达式(与我之前处理其他两个问题的方式相同)来解决这个问题,但我完全被难住了。我什至没有任何东西可以展示,因为我没有任何有用的东西。

那么让我们看看 stackoverflow 社区提出了什么。

最佳答案

这通过了他们所有的测试:

public String plusOut(String str, String word) {
return str.replaceAll(
String.format("(?<!(?=\\Q%s\\E).{0,%d}).", word, word.length()-1),
"+"
);
}

此外,我得到:

plusOut("1xAxAx2", "xAx") → "+xAxAx+"

如果那是您想要的结果,那么我也通过了您的重叠测试,但我不得不承认,那是偶然的。 :D

关于java - codingBat plusOut 使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2628534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com