小编fsd*_*dff的帖子

Java正则表达式:除了给定字符串的实例外,用`+`替换所有字符

我有以下问题说明

使用+符号替换字符串中的所有字符,但方法中给定字符串的实例除外

所以例如,如果给出的字符串是,abc123efg并且他们希望我替换除了每个实例之外的每个字符,123那么它将成为+++123+++.

我认为正则表达式可能是最好的,我想出了这个.

str.replaceAll("[^str]","+") 
Run Code Online (Sandbox Code Playgroud)

其中str是一个变量,但它不允许我使用该方法而不将其放在引号中.如果我只想替换变量字符串str我该怎么做?我用字符串手动输入它运行它,它在方法上工作,但我可以输入一个变量吗?

截至目前我相信它正在寻找字符串"str"而不是变量字符串.

这是除了两个以外的很多情况的输出权:(

在此输入图像描述

开放测试用例列表:

plusOut("12xy34", "xy") ? "++xy++"
plusOut("12xy34", "1") ? "1+++++"
plusOut("12xy34xyabcxy", "xy") ? "++xy++xy+++xy"
plusOut("abXYabcXYZ", "ab") ? "ab++ab++++"
plusOut("abXYabcXYZ", "abc") ? "++++abc+++"
plusOut("abXYabcXYZ", "XY") ? "++XY+++XY+"
plusOut("abXYxyzXYZ", "XYZ") ? "+++++++XYZ"
plusOut("--++ab", "++") ? "++++++"
plusOut("aaxxxxbb", "xx") ? "++xxxx++"
plusOut("123123", "3") ? "++3++3"
Run Code Online (Sandbox Code Playgroud)

java regex

23
推荐指数
2
解决办法
1895
查看次数

这两种算法比较?

所以我遇到了一个问题."确定字符串是否包含所有唯一字符"

所以我编写了这个解决方案,将每个字符添加到一个集合中,但如果该字符已经存在,则返回false.

private static boolean allUniqueCharacters(String s) {

    Set<Character> charSet = new HashSet<Character>();
    for (int i = 0; i < s.length(); i++) {
        char currentChar = s.charAt(i);
        if (!charSet.contains(currentChar)) {
            charSet.add(currentChar);

        } else {
            return false;
        }

    }
    return true;

}
Run Code Online (Sandbox Code Playgroud)

根据我正在阅读的书,这是"最佳解决方案"

public static boolean isUniqueChars2(String str) {
    if (str.length() > 128)
        return false;

    boolean[] char_set = new boolean[128];

    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i);

        if (char_set[val]) {
            return false;
        }
        char_set[val] …
Run Code Online (Sandbox Code Playgroud)

java algorithm

18
推荐指数
1
解决办法
1366
查看次数

标签 统计

java ×2

algorithm ×1

regex ×1