字符串的遍歷
- 字符串的統計
- 判斷字符數組中是否所有的字符都只出現過一次【一行代碼判斷字符串中是否有重復值】(python)
- 統計字符串中連續的重復字符個數(python)
- 找到被指的新類型字符
- 如何截取包含中文的字符串(python)
- 在有序但含有空的數組中查找字符串
- 0左邊必有1的二進制字符串數量
一、字符串的統計
思路:
一個變量count和一個結果變量res,若s[i] == s[i+1],count +=1 ,否則count= 1
代碼:
def getCountStr(s): if not s: return s count = 1 res = '' for i in range(len(s)-1): if s[i] == s[i+1]: count += 1 else: res = res + s[i] + '_' + str(count)+'_' count = 1 res = res + s[len(s)-count] + '_' + str(count) return res s = 'aaabbadddffc' print(getCountStr(s))
二、 判斷字符數組中是否所有的字符都只出現過一次
要求1:采用字典來實現,比較簡單。
要求2:考察排序。
-
- 先將chas排序,排序后相同的字符就放在一起,易判斷有沒有重復字符。
- 重點選擇什么排序算法,保證空間復雜度為O(1)且時間復雜度較小。
-
- 時間O(N)、空間O(1)的沒有排序算法可以做到。
- 時間O(NlogN):歸並【其實遞歸也需要輔助空間】、快排【空間最低O(logN)】、希爾【時間不穩定,可能會變成O(N2)】、堆排序【可以】。
- 結果選擇堆排序,但要用非遞歸來實現,遞歸需要額外的空間。
#思路1:字典 def checkstr(s): if len(s) <= 1: return True dic = {} for i in range(len(s)): if s[i] in dic: return False else: dic[s[i]] = 1 return True #思路2:快速排序 def partition(s,l,r): if not s: return None pivot = s[l] index,small,big = l,l,r while index < big: if s[index] < pivot: s[small] , s[index] = s[index] , s[small] small += 1 index += 1 elif s[index] == pivot: index += 1 else: s[index] , s[big] = s[big],s[index] big -= 1 return small,index def quick_sortStr(s,l,r): if not s: return s if l<r: l1,r1 = partition(s,l,r) quick_sortStr(s,l,l1) quick_sortStr(s,r1,r) return s def checkStr(ss): if not ss: return True s = list(ss) sorts = quick_sortStr(s, 0, len(s)-1) for i in range(len(sorts)-1): if sorts[i] == s[i+1]: return False return True #堆排序 n = 0 def buildTree(arr): global n if not arr: return arr for i in range(n//2-1,-1,-1): adjustTree(arr,i) return arr def adjustTree(arr,i): global n if not arr: return arr maxIndex = i if i*2 + 1 < n and arr[i*2 +1] > arr[maxIndex]: maxIndex = i*2 + 1 if i*2+2 < n and arr[i*2+2] > arr[maxIndex]: maxIndex = i*2 +2 if maxIndex != i: arr[i] , arr[maxIndex] = arr[maxIndex] ,arr[i] adjustTree(arr,maxIndex) return arr def heapSort(arr): global n if not arr: return arr n = len(arr) buildTree(arr) while n > 0: arr[0] , arr[n-1] = arr[n-1] , arr[0] n -= 1 adjustTree(arr,0) return arr def checkStr3(s): if len(s) <= 1: return True arr = list(s) sorts = heapSort(arr) for i in range(len(sorts)-1): if sorts[i] == s[i+1]: return False return True s = 'abcd' print(checkStr3(s))
一行代碼:
print(len(set(s))==len(s))
三、找到被指的新類型字符
思路:從k-1位置開始向左統計大寫字母的數量,根據奇偶性來判斷。
代碼:
def test(s,k): if not s or s == '' or k < 0 or k >= len(s): return '' uNum = 0 for i in range(k-1,-1,-1): if not s[i].isupper(): break uNum += 1 if uNum % 2 == 1: return s[k-1:k+1] if s[k].isupper(): return s[k:k+2] return s[k] s='aaABCDEcNCg' k = 7 test(s,k)