稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。
示例1:
输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
输出:-1
说明: 不存在返回-1。
示例2:
输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
输出:4
示例代码1:
class Solution(object):
def findString(self, words, s):
"""
:type words: List[str]
:type s: str
:rtype: int
"""
location = 0
for i in words:
if i == s:
return location
location += 1
return -1
示例代码2:
class Solution(object):
def findString(self, words, s):
"""
:type words: List[str]
:type s: str
:rtype: int
"""
try:
res = words.index(s)
except:
res = -1
return res
思路解析:
如果直接return words.index(s), s不存在时会出错 所以try...except,捕获到错误时,返回-1
示例代码3(二分查找):
class Solution(object):
def findString(self, words, s):
"""
:type words: List[str]
:type s: str
:rtype: int
"""
a, b = 0, len(words) - 1 # 左右指针
mid = (a+b) // 2 # 初始化
while a
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?