當我連接兩個字串(例如"q5q3q2q1"和"q5q4q3q2q1")時,我得到具有重復子字串的字串,這些字串q5,q3,q2,q1出現了兩次。
結果字串將是"q5q3q2q1q5q4q3q2q1",我需要讓每個子字串 ( q[number]) 出現一次,即"q5q4q3q2q1"。子字串不必以 'q' 開頭,但我可以設定不以數字開頭的限制,也可以有多個數字,如q11.
我可以用什么來獲取這個字串?如果可以用 Java 撰寫解決方案,那就太好了,否則只有演算法才有用。
uj5u.com熱心網友回復:
如果組的順序無關緊要,您可以將連接的字串拆分為組,然后使用一個集合,或者如果它是字典。
a = "q5q3q2q1"
b = "q5q4q3q2q1"
# Concatenate strings
c = a b
print(c)
# Create the groups
d = ["q" item for item in c.split("q") if item != ""]
print(d)
# If order does not matter
print("".join(set(d)))
# If order does matter
print("".join({key: 1 for key in d}.keys()))
uj5u.com熱心網友回復:
另一種解決方案,這個是使用正則運算式。連接字串并找到所有模式([^\d] \d )(regex101)。然后添加找到的字串以設定洗掉重復項并加入它們:
import re
s1 = "q5q3q2q1"
s2 = "q5q4q3q2q1"
out = "".join(set(re.findall(r"([^\d] \d )", s1 s2)))
print(out)
印刷:
q5q2q1q4q3
uj5u.com熱心網友回復:
java正如您所問的那樣,一些快速的方法是:
String a = "q1q2q3";
String b = "q1q2q3q4q5q11";
List l1 = Arrays.asList(a.split("q"));
List l2 = Arrays.asList(b.split("q"));
List l3 = new ArrayList<String>();
l3.addAll(l1);
List l4 = new ArrayList<String>();
l4.addAll(l2);
l4.removeAll(l3);
l3.addAll(l4);
System.out.println(String.join("q", l3));
輸出:
q1q2q3q4q5q11
uj5u.com熱心網友回復:
這是@DanConstantinescu 在 JS 中的解決方案的變體:
- 從連接的字串開始。
- 在由文本后跟數字組成的子字串的開頭拆分字串。這是作為正則運算式前瞻實作的,因此 split 將字串部分作為陣列回傳。
- 從此陣列構建一個集合。建構式執行重復資料洗掉。
- 再次將集合變成陣列
- 將元素與空字串連接起來。
雖然這段代碼不是 Java,但應該可以直接將這個想法移植到其他(命令式或面向物件的)語言中。
let s_concatenated = "q5q3q2q1" "q5q4q3q2q1" "q11a13b4q11"
, s_dedup
;
s_dedup =
Array.from(
new Set(s_concatenated
.split(/(?=[^\d] \d )/) // Split into an array
) // Build a set, deduplicating
) // Turn the set into an array again
.join('') // Concat the elements with the empty string.
;
console.log(`'${s_concatenated}' -> '${s_dedup}'.`);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470752.html
下一篇:將字串添加到用逗號分隔的字串
