leetcode(434,205) python实现
2017-11-17 13:16
218 查看
题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成功:
相关文章推荐
- LeetCode 90 SubsetsII (Python详解及实现)
- 【leetcode】(Python)Reverse Vowels of a String实现字符串内元字符倒序
- leetcode 【 Remove Nth Node From End of List 】 python 实现
- leetcode 【 Reverse Linked List II 】 python 实现
- (LeetCode)Power of Four --- 4的次方,python实现
- leetcode 【 Triangle 】python 实现
- 【leetCode】House Robber python实现
- LeetCode 80 Remove Duplicates from Sorted Array II (Python详解及实现)
- leetcode 【 Remove Element 】python 实现
- leetcode 617. Merge Two Binary Trees Python实现以及and操作符用法
- LeetCode 78. Subsets--Python实现
- 【LeetCode】【Python】【C++】7. Reverse Integer代码实现
- leetcode 【 Find Minimum in Rotated Sorted Array II 】python 实现
- LeetCode 51. N-Queens--Python实现
- 【leetcode】Container with most water--python实现
- leetcode 【 Linked List Swap Nodes in Pairs 】 python 实现
- leetcode 【 Maximum Subarray 】python 实现
- leetcode 【 Linked List Cycle 】 python 实现
- 【leetcode】 46. Permutations ,python实现
- LeetCode 60 Permutation Sequence (Python实现及详解)