434、字符串中的单词数
题目描述:
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: “Hello, my name is John”
输出: 5
方法一:
#最简单的办法len(s.split(' '))
方法二
class Solution(object):
def countSegments(self,s):
count = 1
for i in range(1,len(s)-1):
if str(s[i]) in [' ',',']:
count += 1
if str(s[i]) in [' ',','] and not s[i+1].isalpha():
count -= 1
if i+1>len(s):
break
return count
s = "Hello, my name is John"
solution = Solution()
print solution.countSegments(s)
#方法三
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
count, flag = 0, 0
for i in range(len(s)):
if s[i] != ' ':
flag = 1
elif s[i] == ' ' and flag == 1:
count += 1
flag = 0
return count + flag
463、岛屿周长
题目描述:
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.
Example:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Answer: 16
Solution: 直接遍历二维数组,当前元素为1时,结果加4,判断该元素的上方和左方有无相邻元素,若有则减去相邻的两边,即减2,最后返回结果即可。
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
result = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
result += 4
if i > 0 and grid[i-1][j] == 1:
result -= 2
if j > 0 and grid[i][j-1] == 1:
result -= 2
return result
本文介绍两种算法实现:一是统计字符串中单词的数量,通过分析字符间隔识别单词;二是计算二维网格中岛屿的周长,利用遍历算法确定岛屿边界长度。
1526

被折叠的 条评论
为什么被折叠?



