#一、去除字符串里面的所有空格
replace()方法把字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数max
str.replace(old,new[,max])
a = " welcome to my wolrd ! "
print(a.replace(" ",""))
#也可以用split()切割后合并
print("".join(a.split(" ")))
#二、字符串去重后排序
s = "12nu7d3nduy9rh3bcg"
#1、去重:set(s)
#2、遍历去重
a = []
for i in s:
if i not in a:
a.append(i)
print(a)
#3、排序 sorted()
print(sorted(a))
print("".join())
#三、字符串去重后保留顺序
s = "12nu7d3nduy9rh3bcg"
1、去重:print(set(s))
b = "".join(set(s))
按原顺序 s.index() 索引排序
print("".join(sorted(b,key = lambda x:s.index(x))))
#四、实现菱形
#规律:最大是7,行数7,空格2个
#1,3,5,7,5,3,1
num = eval(input('请输入最多*的所在行数:'))
a = num
b = num
for i in range(1,num+1):
print((a-1)*' ',(2*i-1)*"*") #前面一部分
a -= 1
for j in range(1,num):
print(j*' ',(2*b -3)*"*") #后面一部分,倒序
b -= 1
#力扣算法题:反转字符串中的元音字母 a e o u i,不区分大小写
'''
思路:从字符串第一个,最后一个比较是否是元音字母;如是,则互相交换;
利用双指针进行遍历,先定义第一个index 0,最后一个index len(s)-1,字符串转列表
再列举出集合中所有元素
在 while 最大指针大于最小指针时循环;
判断元素是否在元音字母内,都在就交换值并向前查找;不在则继续向前查找
最后,转为字符串
'''
class Solution:
def reverseV(self, s: str): #s:str的形式定义参数
s = list(s)
low = 0
hight = len(s) - 1
res = set("aeiouAEIOU") # 所有的元音字母,不区分大小写
while low < hight:
if s[low] in res and s[hight] in res:
s[low], s[hight] = s[hight], s[low]
low += 1
hight -= 1
if not s[low] in res:
low += 1
hight -= 1
if not s[hight] in res:
low += 1
hight -= 1
return "".join(s)
R = Solution()
print(R.reverseV("abd2eiousao"))
#力扣算法题:判断一个int类型数值为回文
#方法一
思路:同样采用双指针的方式(),性能高;复杂度: O(n)
class Pdhx:
def hw(self, str1: int):
lst1 = list(str(str1))
n, m = 0, len(str1) - 1
while n < m:
if str1[n] != str1[m]:
return False
n += 1
m -= 1
return True
L = Pdhx()
print(L.hw(123321))
#方法2
思路:双向队列,复杂度: O(n^2) [每次pop(0)都是O(n)..比较费时]
class Pdhx:
def hw(self, str1: int):
lst1 = list(str(str1))
while len(lst) >1:
if str1.pop(0) != str1.pop():
return False
return True
L = Pdhx()
print(L.hw(123321))