劍指offer--python字符串類

題目1
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。
思路:
求所有可能在第一個位置的字符,即把第一個字符和後面的依次交換
固定第一個字符,求後面所有字符的排列。後面所有的字符又可看成第一個字符跟後面所有的字符的排列。典型的遞歸思路
在這裏插入圖片描述

增加一個迭代
# -*- coding:utf-8 -*-
import itertools
class Solution:
    def Permutation(self, ss):
        # write code here
        result=[]
        if not ss:
            return []
        else:
            res=itertools.permutations(ss)
            for i in res:
                if "".join(i) not in result:
                    result.append("".join(i))
        return result

一樣的方法


# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        if not ss:
            return []
        if len(ss) == 1:
            return [ss]
        ret = []
        #遍歷字符串,固定第一個元素,然後遞歸求解
        for i in range(len(ss)):
            for j in self.Permutation(ss[:i]+ss[i+1:]):  注意這裏是s[i:j] 表示獲取a[i]到a[j-1]
                ret.append(ss[i]+j)
        #通過set進行去重,sorted進行重新排序
        return sorted(list(set(ret))) 

題目2
在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫)
思路: 字典

# -*- coding:utf-8 -*-字典方法,注意enumerate 用法
class Solution:
    def FirstNotRepeatingChar(self, s):
        if len(s)<1:
            return -1
        dict={}
        for c in s:
            if c not in dict:
                dict[c]=1
            else:
                dict[c]+=1
        for i ,c in enumerate(s):
            if dict[c]==1:
                return i
        return -1
# -*- coding:utf-8 -*-  直接用count函數
class Solution:
    def FirstNotRepeatingChar(self, s):
        if len(s)<=0 or len(s)>10000:
            return -1
        for i in s:
            if s.count(i)==1:
                return s.index(i)
                break
最差的方法 暴力循環
def IsRepeatingChar(self, i,s):
        for j in range(len(s)):
            if j==i:
                continue
            elif s[j] == s[i]:
                return 0
        return 1
    def FirstNotRepeatingChar(self, s):
        for i in range(len(s)):
            if self.IsRepeatingChar(i,s):
                return i
        return -1

題目3
彙編語言中有一種移位指令叫做循環左移(ROL),現在有個簡單的任務,就是用字符串模擬這個指令的運算結果。對於一個給定的字符序列S,請你把其循環左移K位後的序列輸出。例如,字符序列S=”abcXYZdef”,要求輸出循環左移3位後的結果,即“XYZdefabc”。是不是很簡單?OK,搞定它!
思路:把字符串轉爲列表,把循環左移的前幾位加到列表後面

class Solution:
    def LeftRotateString(self, s, n):
           # write code here
        ans = []
        if s :
            lists=list(s)#字符串轉換爲列表
            #ind = n%len(lists)
            ans = lists[n:]
            ans.extend(lists[0:n])
        return ''.join(ans)

題目4–把字符串轉換爲整數

將一個字符串轉換成一個整數(實現Integer.valueOf(string)的功能,但是string不符合數字要求時返回0),要求不能使用字符串轉換整數的庫函數。 數值爲0或者字符串不是一個合法的數值則返回0。
思路:

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        numlist=['0','1','2','3','4','5','6','7','8','9','+','-']
        sum=0
        label=1#正負數標記
        if s=='':  #如果爲空,則返回0
            return 0
        for string in s: #對於字符串裏面的字符
            if string in numlist:#如果是合法字符 
                if string=='+':
                    label=1
                    continue
                if string=='-':
                    label=-1
                    continue
                else:
                    sum=sum*10+numlist.index(string)  #計算總數 
            if string not in numlist:#非合法字符
                sum=0
                break#跳出循環
        return sum*label

題目5-表示數值的字符串

請實現一個函數用來判斷字符串是否表示數值(包括整數和小數)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示數值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。

思路,比較瑣碎,需要把一些特殊情況給排除

# -*- coding:utf-8 -*-
class Solution:
    # s字符串
    def isNumeric(self, s):
        # write code here
        if s is None or len(s) == 0:
            return False

        # 是否有e
        hasE = False
        # 是否有小數
        isDecimal = False
        # 是否有+-符號
        hasSign = False

        for i in range(len(s)):
            # 如果有e,只能有一個e且不能是最後一個
            if s[i] == "e" or s[i] == "E":
                if hasE or i == len(s) - 1:
                    return False
                hasE = True
            # 小數點不能重複出現或和e共線
            elif s[i] == ".":
                if hasE or isDecimal:
                    return False
                isDecimal = True
            elif s[i] == "-" or s[i] == "+":
                # 重複出現符號時,必須跟在e後面
                if hasSign and s[i - 1] != "e" and s[i - 1] != "E":
                    return False
                # 重複出現符號時,必須跟在e後面
                if not hasSign and i > 0 and s[i - 1] != "e" and s[i - 1] != "E":
                    return False
                hasSign = True
            elif s[i] < "0" or s[i] > "9":
                return False
        return True
        # write code here

題目6-字符流中第一個不重複的數字
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"go"時,第一個只出現一次的字符是"g"。當從該字符流中讀出前六個字符“google"時,第一個只出現一次的字符是"l"。如果當前字符流沒有存在出現一次的字符,返回#字符。

思路: 應用字典

# -*- coding:utf-8 -*-
class Solution:
    # 返回對應char
    def __init__(self):
        self.c = ""
        self.d = {}
    def FirstAppearingOnce(self): #檢測第一次只出現一次的字符
        for s in self.c:
            if self.c.count(s) == 1:
                return s
        return "#"
    def Insert(self, char): # 字符流中輸入數據
        self.c = self.c + (char)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章