5 回答
TA贡献1775条经验 获得超8个赞
这个遵循两个规则
x='ABCDEAB'
for i in x:
try:
if(i in x[x.index(i)+1:]):
print(i,end=" ")
x=x.replace(i,"",1)
except ValueError:
pass
TA贡献1829条经验 获得超13个赞
sample_string = "ABCDEAB"
for index in range(len(sample_string)):
if sample_string[index] in sample_string[index + 1 :]:
print(sample_string[index], end="")
TA贡献1789条经验 获得超8个赞
这是我能够用 Java 绘制的解决方案,我猜你可以在 python 中尝试相同的逻辑:
/*
* Rules:
* 1. i should not be greater then str.lenght()-1
* 2. j should be greater then i
* 3. if str.charAt[i] == str.charAt[j] then reset j to str.lenght()-1 and increment i
* 4. if str.charAt[i] == str.charAt[j] then decrement j but no change to i
* 5. if j <= i then increment i and set j to str.lenght()
*/
public void algorithm(String str) {
for(Integer i=0, j=str.length()-1; i < str.length() && j > i; i++, j--) {
if (str.charAt(i) == str.charAt(j)) {
System.out.println(str.charAt(i)+" Char Matched");
j = str.length();
}
else {
i--;
if (j-1 <= i+1) {
i++;
j = str.length();
}
}
}
}
TA贡献1995条经验 获得超2个赞
使用计数器:
from collections import Counter
word = "ABCDEAB"
print([k for k, v in Counter(word).items() if v > 1]) # ['A', 'B']
使用列表理解:
word = "ABCDEAB"
print([k for k in set(word) if word.count(k) > 1])
编辑:如果理解有问题,请立即打印:
word = "ABCDEAB"
for k in set(word):
if word.count(k) > 1:
print(k)
TA贡献1829条经验 获得超4个赞
由于没有其他人这样做,即使它不是很 Pythonic,我也提出了一个使用递归的解决方案。它应该符合“无循环”要求,并且除了输入字符串之外根本不使用任何变量(当然无论如何都会使用一些隐藏的堆栈空间)
# Count Characters Appearing more than once in String
def nbdup(s):
if len(s) < 2:
return 0
if s.count(s[0]) == 2:
print(s[0])
return 1 + nbdup(s[1:])
return nbdup(s[1:])
print(nbdup("ABCDEAB"))
添加回答
举报
