找出字符串中第一个只出现一次的字符
数据范围:输入的字符串长度满足
while True: try: str1 = input() str2 = ""#用于去除重复项,不能用set()因为会打乱而这个要求第一个出现一次 for i in range (len(str1)): if str1[i] not in str2: str2 = str2 + str1[i]#当为第一次出现时添加项 counter = 0 succ = 0 for i in range (len(str2)): counter = str1.count(str2[i])#按序查找出现次数 if counter == 1: print(str2[i]) succ = 1 break#一旦出现第一个只出现一次的跳出循环 if succ == 0:#没有时返回-1 print(-1) except: break
第一种用字典,统计好每个字符的个数之后,从字典里按顺序找到个数为1的字符输出就可以了。
用字典处理的方法可以用的题目相对而言广泛一点,可以用来处理更复杂一点的问题。
while True: try: s = list(input()) dic = {} char = -1 for i in range(len(s)): if s[i] in dic: dic[s[i]] += 1 else: dic[s[i]] = 1 for i in dic: if dic[i] == 1: char = i break print(char) except EOFError: break
就这道题目而言,下面这种不用字典,直接count的方法更简单
while True: try: s = list(input()) char = -1 for i in s: if s.count(i) == 1: char = i break print(char) except EOFError: break
while True: try: s = input().strip() d = {} for i in s: d[i] = d.get(i, 0) + 1 count = 0 for i in s: if d[i] == 1: print(i) count += 1 break if not count: print(-1) except: break
import sys from collections import OrderedDict for s in sys.stdin: s = s.strip() repeated_chars, once_chars = set(), OrderedDict() for c in s: if c in once_chars: once_chars.pop(c) repeated_chars.add(c) elif c not in repeated_chars: once_chars[c] = 1 if not once_chars: print(-1) else: k ,v = once_chars.popitem(last=False) print(k)
while True: try: a = input().strip() for i in a: if a.count(i) == 1: print(i) break else: print(-1) except: break
from collections import defaultdict while True: try: s = input() dd = defaultdict(list) for i, v in enumerate(s): if not dd[v]: dd[v].extend([1, i]) else: dd[v][0] += 1 # 先按照出现的次数排序,再按照出现的先后排序 dd = sorted(dd.items(), key=lambda x:(x[1][0], x[1][1])) if dd[0][1][0] == 1: print(dd[0][0]) else: print(-1) except: break