python_lintcode_685First Unique Number In Stream_157判断字符串是否没有重复字符
2017-09-27 12:12
453 查看
685First Unique Number In Stream
题目
http://www.lintcode.com/zh-cn/problem/first-unique-number-in-stream/Given a continuous stream of numbers, write a function that returns the first unique number whenever terminating number is reached(include terminating number). If there no unique number before terminating number or you can’t find this terminating number, return -1.
Have you met this question in a real interview? Yes
Example
Given a stream [1, 2, 2, 1, 3, 4, 4, 5, 6] and a number 5
return 3
Given a stream [1, 2, 2, 1, 3, 4, 4, 5, 6] and a number 7
return -1
思路
题目解释:nums列表中,第一个出现number之前(包括number)判断是否出现单独的数,若有,返回第一个的单独的数,否则返回-1程序思路
先确定需要判断的子集合:
情况一:number在nums中,子集合为nums[:nnums.index(number)+1]
情况二:number不在nums中,直接返回-1
将子集合中的元素全部存入新建的字典dict,字典的一个特点:当键出现一样时,键值会等于最后的一个键出现键值,这个特点可以让我们确定哪个不是重复的数,不是重复的数,它在子集合的下标=字典中该数的键值
python内的字典存储时候会按键升序,所以需要将改变排序的方式,为按键值排序,这样才和子集合一致
-字典的按键或按键值排序
http://blog.csdn.net/xsj_blog/article/details/51847831
将按键值排序的元祖yz(字典变排序方式后变成(键,键值)的元祖,其中yz[0]键,yz[1]键值)和子集合进行比较,若yz[1]==子集合.index(yz[0]),则该键是单独的,返回该数
否则,返回-1
-字典的按键或按键值排序
http://blog.csdn.net/xsj_blog/article/details/51847831
代码
class Solution: """ @param: : a continuous stream of numbers @param: : a number @return: returns the first unique number """ def firstUniqueNumber(self, nums, number): # Write your code here #确定子集合 if nums==[]:return -1 if number in nums: son_nums=nums[:nums.index(number)+1] else:return -1 #建立字典,得到一个键为子集合元素,键值为子集合最新出现元素的下标 #生成的字典是按键升序的,不符合要求,应该是键值升序 dict={} for i in range(len(son_nums)): dict[son_nums[i]]=i #将字典按键值进行升序,变成元组 yz=sorted(dict.items(), key=lambda dict:dict[1]) #遍历元组,y[0]为键,y[1]为键值 for j in yz: if j[1]==son_nums.index(j[0]): #若相同则输出该值 return j[0] return -1
157判断字符串是否没有重复字符
题目
http://www.lintcode.com/zh-cn/problem/unique-characters/实现一个算法确定字符串中的字符是否均唯一出现
Have you met this question in a real interview? Yes
Example
给出”abc”,返回 true
给出”aab”,返回 false
思路
借用上面题目的一些思路字典的键值存的是该键在字符串的总数
当循环字典,发现键值大于1时,则返回False
否则返回True
代码
class Solution: """ @param: str: A string @return: a boolean """ def isUnique(self, str): # write your code here dict={} for i in range(len(str)): dict[str[i]]=str.count(str[i]) for i in dict: if dict[i]>1: return False return True
相关文章推荐
- LintCode_157_判断字符串是否没有重复字符
- lintcode-157-判断字符串是否没有重复字符
- 【LintCode 简单】157. 判断字符串是否没有重复字符
- 157 - 判断字符串是否没有重复字符
- LintCode-判断字符串是否没有重复字符
- 【Lintcode】判断字符串是否没有重复字符
- Lintcode 容易 python 判断字符串是否没有重复字符
- 判断字符串是否没有重复字符-LintCode
- Lintcode 157. 判断字符串是否没有重复字符
- 日常练习:lintcode 157. 判断字符串是否没有重复字符
- 算法学习(java实现之字符串篇)·····判断字符串是否没有重复字符
- 判断字符串中是否没有重复的字符
- LintCode Unique Characters 判断字符串是否没有重复字符
- 判断字符串是否没有重复字符(容易)
- 判断字符串是否没有重复字符
- 题目:判断字符串是否没有重复字符
- 判断字符串是否没有重复字符
- lintcode 容易题:Unique Characters 判断字符串是否没有重复字符
- 判断字符串是否没有重复字符
- Java实现-判断字符串是否没有重复字符