我有以下问题说明
使用
+
符号替换字符串中的所有字符,但方法中给定字符串的实例除外
所以例如,如果给出的字符串是,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) 所以我遇到了一个问题."确定字符串是否包含所有唯一字符"
所以我编写了这个解决方案,将每个字符添加到一个集合中,但如果该字符已经存在,则返回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)