字符串算法总结

字符串算法总结

替换空格(没什么好说的,白给题)

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        l = len(s.split(' '))
        a = ''
        for i in range(l-1):
            a += s.split(' ')[i] + '%20'
        a = a+s.split(' ')[l-1]
        return a

字符串的全排列

class Solution:
    def Permutation(self, ss):
        if len(ss) <= 1:
            return ss
        res = set()
        # 遍历字符串,固定第一个元素,第一个元素可以取a,b,c...,然后递归求解
        for i in range(len(ss)):
            for j in self.Permutation(ss[:i] + ss[i+1:]): # 依次固定了元素,其他的全排列(递归求解)
                res.add(ss[i] + j) # 集合添加元素的方法add(),集合添加去重(若存在重复字符,排列后会存在相同,如baa,baa)
        return sorted(res)         # sorted()能对可迭代对象进行排序,结果返回一个新的list

第一次只出现一次的字符(哈希)

class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here

        ls=[0]*256
        #遍历字符串,下标为ASCII值,值为次数
        for i in s:
            ls[ord(i)]+=1
        #遍历列表,找到出现次数为1的字符并输出位置
        for j in s:
            if ls[ord(j)]==1:
                return s.index(j)
        return -1

左旋字符串(两次翻转)

# -*- coding:utf-8 -*-
class Solution:
 
    def reverse(self, s):
        if not s:
            return ""
 
        length = len(s)
        if length <= 0:
            return ""
 
        s = list(s)
        #print s
        start = 0
        end = length - 1
        while start < end:
            s[start], s[end] = s[end], s[start]
            start += 1
            end -= 1
        #print 'after', s
        return ''.join(s)
     
 
    def LeftRotateString(self, s, n):
        # write code here
        if not s:
            return ""
        length = len(s)
        if length <= 0:
            return ""
        if n > length:
            n = n % length
 
        s = self.reverse(s)
 
        first = ""
        second = ""
        for i in range(length - n):
            first += s[i]
        first = self.reverse(first)
        for i in range(length - n, length, 1):
            second += s[i]
        second = self.reverse(second)
        return first + second
            

判断字符串是否为合法数字

class Solution:
    def StrToInt(self, s):
        # write code here
        # 先排除异常特殊情况
        if s in ['','-','+','+-','-+']:
            return 0
        count = 0
        # 只要有非法字符就不过
        for i in s:
            # 检查字母
            if i not in '0123456789+-':
                count += 1
        # 只要-+号不在第一位就不过
        for i in s[1:]:
            if i not in '0123456789':
                count += 1
        if count:
            return 0
        return int(s)

你可能感兴趣的:(python的使用,算法)