是否有任何有效的方法(不包括“包含”或“indexOf”方法)從給定的字串中洗掉重復字符(包括)。
例如:
輸入:"abcdcb"
輸出:"ad"
輸入:"abracadabra"
輸出:"cd"
我曾嘗試使用 RegEx,但出現了問題:
public static String function(String str) {
return str.replaceAll("([a-z] )\\1", "");
}
編輯:最長,非有效的解決方案:
public static String function(String s) {
String result = "";
for (int i = 0; i < s.length(); i )
if(s.length() - s.replace("" s.charAt(i), "").length() == 1)
result = "" s.charAt(i);
return result;
}
uj5u.com熱心網友回復:
單個正則運算式無法做到這一點。
正如 Pshemo 建議的那樣,創建一個統計字符出現次數的 Map:
Map<Integer, Long> codePointCounts = s.codePoints().boxed().collect(
Collectors.groupingBy(
c -> c, LinkedHashMap::new, Collectors.counting()));
(使用 LinkedHashMap 將保留代碼點在 Map 中的順序。)
然后丟棄所有計數不為 1 的 Map 條目:
codePointCounts.values().retainAll(Set.of(1L));
洗掉 Map 值將洗掉其對應的鍵,因此任何剩余的 Map 鍵都是原始字串中的唯一代碼點。您可以從整數陣列創建字串:
int[] codePoints = codePointCounts.keySet().stream()
.mapToInt(Integer::intValue).toArray();
String uniqueChars = new String(codePoints, 0, codePoints.length);
uj5u.com熱心網友回復:
這是另一種方法。我將字符映射到 int 陣列的索引。該陣列用于計算字符在字串中出現的次數。如果計數為零,那么它是第一次被看到,所以它被添加到 char 陣列 r 中。最后,我們回傳一個從 char 陣列 r 構造的字串。
public static String function(String s) {
int[] a = new int[27];
char[] r = new char[s.length()];
int len = 0;
for(int i=0; i<s.length(); i )
if (a[s.charAt(i)-'a'] ==0)
r[len ] = s.charAt(i);
return new String(r, 0, len);
}
uj5u.com熱心網友回復:
使用VGR的方法,但只使用java.util.stream
String value="abracadabra";
String uniqueChars = Arrays.asList(value.split("")) //creating a list from String
.stream()
.collect(Collectors.groupingBy(s->s,LinkedHashMap::new, Collectors.counting())) // grouping by all values with their no of occurrences(as count)
.entrySet() //after creating the map traversing through the entryset
.stream()
.filter(m->m.getValue()==1L) // fetch values which have count=1
.map(Map.Entry::getKey)
.collect(Collectors.joining());
System.out.println(uniqueChars);
//output = cd
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496164.html
下一篇:如何在Dartt中做到這一點$current_segment=~s/([a-zA-Z] )\.([a-zA-Z] )/$1punto$2/g;
