刷题之字符串/数组
1,剑指offer-39:求重复数组中出现一半及以上的数字
nums = [2, 2, 2, 3, 3, 4]
len_nums = len(nums)
if len_nums < 2:
return 0
# 先计算出现最多次数的值是什么
res = nums[0]
count = 1
for i in range(1, len_nums):
# 必须先判断count是否为0
if count == 0:
res = nums[i]
count = 1
# 再看是否相等,相等加1,否则减1
elif nums[i] != res:
count -= 1
elif nums[i] == res:
count += 1
count_double = 0
# 判断是否超过一半
for j in nums:
if j == res:
count_double += 1
if count_double >= len_nums//2:
return res
else:
return 0
2,最长无重复子数组
题目:
给定一个数组arr,返回arr的最长无重复元素子数组的长度,无重复指的是所有数字都不相同。子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组。
eg:
输入:
[1,2,3,1,2,3,2,2]
返回值:
3
说明:
最长子数组为[1,2,3]
解法1
l = len(arr)
max_val = 0
l_str = {}
j = -1
for i in range(l):
if arr[i] in l_str and j < l_str[arr[i]]:
j = l_str[arr[i]]
l_str[arr[i]] = i
if (i - j) > max_val:
max_val = i - j
return max_val
解法2(双指针)
nums = [1,2,3,1,2,3,2,2]
len_num = len(nums)
slow = 0
fast = 1
result = []
temp = []
while slow < len_num and fast < len_num:
if nums[slow] not in temp:
temp.append(nums[slow])
elif nums[fast] not in temp:
temp.append(nums[fast])
fast += 1
else:
slow += 1
fast += 1
if len(temp) > len(result):
temp, result = [], temp
if temp and not result:
temp, result = [], temp
return result
3,合并两个有序的数组
# @param A int整型一维数组
# @param B int整型一维数组
# @return void
#
class Solution:
def merge(self , A, m, B, n):
# write code here
while m > 0 and n > 0:
if A[m-1] >= B[n-1]:
A[m+n-1] = A[m-1]
m-=1
else:
A[m+n-1] = B[n-1]
n-=1
if n > 0: A[:n] = B[:n]
4,括号序列
题目:给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法
# @param s string字符串
# @return bool布尔型
#
class Solution:
def isValid(self , s ):
# write code here
stack = []
for i in s:
if i == '(' or i == '[' or i == '{':
stack.append(i)
elif i == ')':
if len(stack) == 0 or stack.pop() != '(':
return False
elif i == '}':
if len(stack) == 0 or stack.pop() != '{':
return False
elif i == ']':
if len(stack) == 0 or stack.pop() != '[':
return False
return len(stack) == 0
5,数组中相加和为0的三元组
题目:
给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。注意:
三元组(a、b、c)中的元素必须按非降序排列。(即a≤b≤c)
解集中不能包含重复的三元组。
eg:
输入:
[-2,0,1,1,2]
返回值:
[[-2,0,2],[-2,1,1]]
# @param num int整型一维数组
# @return int整型二维数组
#
class Solution:
def threeSum(self , num ):
# write code here
res = []
if len(num) < 3:
return res
num.sort()
for i in range(len(num)-2):
if num[i] > 0:
break
if i>0 and num[i] == num[i-1]:
continue
left = i+1
right = len(num) - 1
while left < right:
sum = num[i] + num[left] + num[right]
if sum == 0:
res_se = []
res_se.append(num[i])
res_se.append(num[left])
res_se.append(num[right])
res.append(res_se)
while left < right and num[left] == num[left+1]:
left += 1
while left < right and num[right] == num[right-1]:
right -= 1
left += 1
right -= 1
elif sum > 0:
right -= 1
elif sum < 0:
left += 1
return res
6,数组中出现次数超过一半的数字
题目:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。你可以假设数组是非空的,并且给定的数组总是存在多数元素。1<=数组长度<=50000
eg:
输入:
[1,2,3,2,2,2,5,4,2]
返回值:
2
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if len(numbers) == 1:
return numbers[0]
numbers.sort()
count = 1
res = numbers[0]
for i in range(1,len(numbers)):
if count == 0:
res = numbers[i]
count = 1
elif res == numbers[i]:
count += 1
elif res != numbers[i]:
count -= 1
counts = 0
for i in numbers:
if i == res:
counts += 1
if counts >= len(numbers) // 2:
return res
else:
return None
7,最长回文字符串
解法1:暴力法
class Solution:
def getLongestPalindrome(self, A, n):
if n == 0 or A == A[::-1]:
return n
count = 0
for i in range(len(A)):
for j in range(i, len(A)):
if self.sort_a(A[i:j]):
length = len(A[i:j])
if length > count:
count = length
return count
def sort_a(self, a):
if a == a[::-1]:
return True
else:
return False
解法2:
class Solution:
def expandAroundCenter(self, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return left + 1, right - 1
def longestPalindrome(self, s: str) -> str:
start, end = 0, 0
for i in range(len(s)):
# 字符串为奇数个时
left1, right1 = self.expandAroundCenter(s, i, i)
# 字符串为偶数个时
left2, right2 = self.expandAroundCenter(s, i, i + 1)
if right1 - left1 > end - start:
start, end = left1, right1
if right2 - left2 > end - start:
start, end = left2, right2
return s[start: end + 1]

浙公网安备 33010602011771号