【LeetCode刷题】434 字符串中单词数 || 463 岛屿的周长

本文介绍两种算法实现:一是统计字符串中单词的数量,通过分析字符间隔识别单词;二是计算二维网格中岛屿的周长,利用遍历算法确定岛屿边界长度。

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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jeremy-Sky

你的鼓励是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值