猿问

使用一个没有变量的 for 循环查找字符串中重复字符的数量

我被问到一个 Python 开发人员职位的面试问题。一切顺利,但有一个问题我无法回答——问题是:

查找具有以下限制的字符串中重复的字符数:

  1. 您只能使用一个 for 循环或 while 循环。

  2. 不能用列表、字典或任何会消耗内存的东西定义新变量。

字符串中的字母可以按任何顺序排列。

例子:

x="ABCDAB"

解决方案:

AB

输出可以以任何格式传递,但需要识别字符。


斯蒂芬大帝
浏览 183回答 5
5回答

www说

这个遵循两个规则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

烙印99

sample_string = "ABCDEAB"for index in range(len(sample_string)):    if sample_string[index] in sample_string[index + 1 :]:        print(sample_string[index], end="")

拉丁的传说

这是我能够用 Java 绘制的解决方案,我猜你可以在 python 中尝试相同的逻辑:/*&nbsp;* Rules:&nbsp;* 1. i should not be greater then str.lenght()-1&nbsp;* 2. j should be greater then i&nbsp;* 3. if str.charAt[i] == str.charAt[j] then reset j to str.lenght()-1 and increment i&nbsp;* 4. if str.charAt[i] == str.charAt[j] then decrement j but no change to i&nbsp;* 5. if j <= i then increment i and set j to str.lenght()&nbsp;*/public void algorithm(String str) {&nbsp; &nbsp; for(Integer i=0, j=str.length()-1; i < str.length() && j > i; i++, j--) {&nbsp; &nbsp; &nbsp; &nbsp; if (str.charAt(i) == str.charAt(j)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str.charAt(i)+" Char Matched");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j = str.length();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (j-1 <= i+1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j = str.length();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

拉风的咖菲猫

使用计数器:from collections import Counterword = "ABCDEAB"print([k for k, v in Counter(word).items() if v > 1])&nbsp; # ['A', 'B']使用列表理解:word = "ABCDEAB"print([k for k in set(word) if word.count(k) > 1])编辑:如果理解有问题,请立即打印:word = "ABCDEAB"for k in set(word):&nbsp; if word.count(k) > 1:&nbsp; &nbsp; print(k)

浮云间

由于没有其他人这样做,即使它不是很 Pythonic,我也提出了一个使用递归的解决方案。它应该符合“无循环”要求,并且除了输入字符串之外根本不使用任何变量(当然无论如何都会使用一些隐藏的堆栈空间)# Count Characters Appearing more than once in Stringdef nbdup(s):&nbsp; &nbsp; if len(s) < 2:&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; if s.count(s[0]) == 2:&nbsp; &nbsp; &nbsp; &nbsp; print(s[0])&nbsp; &nbsp; &nbsp; &nbsp; return 1 + nbdup(s[1:])&nbsp; &nbsp; return nbdup(s[1:])print(nbdup("ABCDEAB"))
随时随地看视频慕课网APP

相关分类

Python
我要回答