【发布时间】:2018-02-02 01:52:46
【问题描述】:
如此处所述: https://leetcode.com/problems/first-unique-character-in-a-string/description/
我在这里尝试了一个,但无法完成: https://paste.pound-python.org/show/JuPLgdgqceMQYh5kk0Sf/
#Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
#xamples:
#s = "leetcode"
#return 0.
#s = "loveleetcode",
#return 2.
#Note: You may assume the string contain only lowercase letters.
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
for i in range(len(s)):
for j in range(i+1,len(s)):
if s[i] == s[j]:
break
#But now what. let's say i have complete loop of j where there's no match with i, how do I return i?
我只对蛮力 N^2 解决方案感兴趣,没有什么比这更有趣的了。上述方案的思路是启动一个双循环,其中内循环搜索与外循环的字符匹配,如果匹配,则中断内循环并继续到外循环的下一个字符。
但问题是,当没有匹配项时,我该如何处理,也就是我需要将外部循环的索引作为第一个唯一索引返回时。
无法找到一种优雅的方式来处理它,并且可以像处理单个字符字符串一样处理边缘情况。
【问题讨论】: