字符串经典基础面试题:轻松掌握,征服代码之路
2023-05-07 17:59:34
在编程领域,字符串是无处不在的数据类型,是面试官青睐的考点之一。掌握字符串的基础算法,可以让我们在面试中游刃有余,展现出扎实的技术功底。
1. 字符串反转
将字符串中的字符顺序颠倒,例如将“hello”反转为“olleh”。
def reverse_str(s):
return s[::-1]
s = "hello"
print(reverse_str(s)) # 输出: olleh
2. 字符串查找
在字符串中找出子字符串的起始位置,例如在“hello world”中找出“world”的位置(6)。
def find_str(s, sub):
return s.find(sub)
s = "hello world"
sub = "world"
print(find_str(s, sub)) # 输出: 6
3. 字符串替换
将字符串中的子字符串替换为另一个字符串,例如将“hello world”中的“world”替换为“Python”。
def replace_str(s, sub, rep):
return s.replace(sub, rep)
s = "hello world"
sub = "world"
rep = "Python"
print(replace_str(s, sub, rep)) # 输出: hello Python
4. 字符串分割
将字符串按照指定分隔符分割成列表,例如将“hello,world,Python”按照逗号分隔为['hello', 'world', 'Python']。
def split_str(s, sep):
return s.split(sep)
s = "hello,world,Python"
sep = ","
print(split_str(s, sep)) # 输出: ['hello', 'world', 'Python']
5. 字符串连接
将两个字符串连接成一个新的字符串,例如将“hello”和“world”连接为“helloworld”。
def join_str(s1, s2):
return s1 + s2
s1 = "hello"
s2 = "world"
print(join_str(s1, s2)) # 输出: helloworld
6. 字符串格式化
将字符串中的占位符替换为指定的参数,例如将“hello, {name}”格式化为“hello, John”。
def format_str(s, **kwargs):
return s.format(**kwargs)
s = "hello, {name}"
kwargs = {"name": "John"}
print(format_str(s, **kwargs)) # 输出: hello, John
7. 字符串比较
比较两个字符串的大小,返回-1(小于)、0(相等)或1(大于),例如“hello”小于“world”。
def compare_str(s1, s2):
return cmp(s1, s2)
s1 = "hello"
s2 = "world"
print(compare_str(s1, s2)) # 输出: -1
8. 字符串排序
将字符串列表按照某种顺序进行排序,例如将['hello', 'world', 'Python']排序为['hello', 'Python', 'world']。
def sort_str(slist):
return sorted(slist)
slist = ['hello', 'world', 'Python']
print(sort_str(slist)) # 输出: ['hello', 'Python', 'world']
9. 字符串哈希
计算字符串的哈希值,用于快速查找和比较字符串,例如计算“hello”的哈希值。
def hash_str(s):
return hash(s)
s = "hello"
print(hash_str(s)) # 输出: 某个整数
10. 字符串加密
将字符串加密为不可读的格式,例如将“hello”加密为“aGVsbG8=”。
import base64
def encrypt_str(s):
return base64.b64encode(s.encode('utf-8'))
s = "hello"
print(encrypt_str(s)) # 输出: aGVsbG8=
常见问题解答
1. 字符串反转算法的时间复杂度是多少?
线性的,与字符串长度成正比。
2. 如何将字符串转换为整数?
使用 int()
函数,例如 int("123")
。
3. 如何在字符串中查找所有匹配子字符串?
使用 re.findall()
函数,例如 re.findall("world", "hello world, world!")
。
4. 如何统计字符串中字符出现的次数?
使用 collections.Counter()
,例如 Counter("hello")
。
5. 如何将字符串中的大写字母转换为小写字母?
使用 lower()
方法,例如 "HELLO".lower()
。
结语
掌握字符串的基础算法对于提升编程能力和面试表现至关重要。通过练习这些算法,我们可以加深对字符串操作的理解,成为一名更加全面的程序员。