leetcode(434,205) python实现

题434:

题目要求寻找一个字符串中的不同部分的数量,大体思路是寻找“ ”空格的数量,其中要考虑的是:
1.必须前一个是“ ”,后一个不是“ ”,才使num+1,避免连续空格的出现,误加num
2.对于没有空格出现的一个单词,返回1
3.对于以空格开头的单词,返回num, 不以空格开头的单词,返回num+1

代码如下:

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        num  = 0
        if len(s)==0:
            return  0
        for i in range(len(s)-1):
           if  s[i] == ' ' and s[i+1] !=' ':
               num  += 1
        if num == 0 and s[0]==' ':
            return 0
        elif num == 0 and s[0] != ' ':
            return 1
        elif num != 0 and s[0] !=' ':
            return num +1
        elif num != 0 and s[0] == ' ':
            return num


s = Solution()
nu = '  '
print(s.countSegments(nu))

这里写图片描述

最后通过submit
这里写图片描述

题205

题目要求:
给定两个string字符串,判断它俩是否同形,具体如下:
Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given “egg”, “add”, return true.

Given “foo”, “bar”, return false.

Given “paper”, “title”, return true.
我的思路是:
1.count1中保存s第一次出现的字母,count2保存t中第一次出现的字母。
2.一个for循环,如果s[i]第一次出现,就append到count1,如果t[i]第一次出现就append到count2。如果s[i]不是第一次出现,首先找到第一次出现该值的位置index,然后判断t中该位置是否和s是一样的模式,即比较该位置的值t[i]是否和t[index]相等,相等即模式一致。
3.最后要判断count1和count2的长度是否相等,这是为了避免如果一个字母出现的模式和s中一致,但是这个字母在s中这些位置以外的地方出现,前面的判断会察觉不到,这里就能判断出这个问题。

代码如下:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """

        count1 = []
        count2 = []
        if len(s) <= 1:
            return True
        else:
            for i in range(len(s)):
                if t[i] not in count2:
                    count2.append(t[i])
                if s[i] not in count1:
                    count1.append(s[i])

                else:
                    index = s.index(s[i])
                    if t[i] != t[index]:
                        return False
            if len(count2)==len(count1):
                return True
            else:
                return False
s = Solution()
s1 = 'abcb'
s2 = 'bacb'
t(s.isIsomorphic(s1,s2))

结果:
这里写图片描述

最后submit成功:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值