1. 从字符串中找出第一个重复的字符
比如"abcdefgabcdefg"第一个重复的字符是’a’
- 遍历字符串,将字符存入新的列表中, 如果字符在新的列表中存在, 则返回该字符
def get_first_duplicated_char(string):
uniq_chars = set()
for c in list(string):
if c not in uniq_chars:
uniq_chars.add(c)
else:
return c
- 对所有字符进行计数
import string
def get_first_duplicated_char(s):
all_chars = dict(zip(string.printable, [0] * len(string.printable), ))
for c in s:
all_chars[c] += 1
if all_chars[c] == 2:
return c
2. 对一段字符串中的电子邮件进行脱敏处理
比如把send email to melody_zkm@gmail.com, melody.zkm@alibaba-inc.com and zkm2000@gov.com.cn 中的邮箱地址全部替换成 ******
import re
def encrypt_emais(string):
match_emails = re.findall(r'(\w+\.*\w+\@\w+\-*\w*\.\w+\.*\w*)', s)
for email in match_emails:
string = re.sub(email, '******', string)
return string
3. 将一段语句翻转, 但是不翻转语句中的单词
s = “I am a student”
return “student a am I”
def reverse_sentence(sentence):
return ' '.join(reversed(sentence.split(' ')))
4. 两个字符串包含的字符是否完全相同
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
字符串只包含小写字符,总共有 26 个小写字符。可以用 HashMap 来映射字符与出现次数。因为键的范围很小,因此可以使用长度为 26 的整型数组对字符串出现的字符进行统计,然后比较两个字符串出现的字符数量是否相同。
from collections import Counter
def if_contains_same_amount_chars(s1, s2):
count1 = Counter(s1)
count2 = Counter(s2)
if count1 == count2:
return True
else:
return False