为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

斯蒂芬大帝 2023-02-07 16:01:44
我被问到一个 Python 开发人员职位的面试问题。一切顺利,但有一个问题我无法回答——问题是:查找具有以下限制的字符串中重复的字符数:您只能使用一个 for 循环或 while 循环。不能用列表、字典或任何会消耗内存的东西定义新变量。字符串中的字母可以按任何顺序排列。例子:x="ABCDAB"解决方案:AB输出可以以任何格式传递,但需要识别字符。
查看完整描述

5 回答

?
www说

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


查看完整回答
反对 回复 2023-02-07
?
烙印99

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="")


查看完整回答
反对 回复 2023-02-07
?
拉丁的传说

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();

            }

        }

    }

}


查看完整回答
反对 回复 2023-02-07
?
拉风的咖菲猫

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)


查看完整回答
反对 回复 2023-02-07
?
浮云间

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"))


查看完整回答
反对 回复 2023-02-07
  • 5 回答
  • 0 关注
  • 182 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号