[Data Structure Study Plan] - Day 5
387. First Unique Character in a String
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
Solution 1:
class Solution:
def firstUniqChar(self, s):
for i in s:
if s.count(i) == 1:
return s.index(i)
return -1
Feedback:
Runtime: 4872 ms, faster than 5.00% of Python3 online submissions for First Unique Character in a String.
Memory Usage: 14.2 MB, less than 85.28% of Python3 online submissions for First Unique Character in a String
Solution 2:
class Solution:
def firstUniqChar(self, s):
return min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1])
Remark: same idea with solution 1, but improved with built-in function string.ascii_lowercase.
Feedback:
Runtime: 52 ms, faster than 99.19% of Python3 online submissions for First Unique Character in a String.
Memory Usage: 14.2 MB, less than 85.28% of Python3 online submissions for First Unique Character in a String.
383. Ransom Note
Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed from magazine
and false
otherwise.
Each letter in magazine
can only be used once in ransomNote
.
class Solution:
def canConstruct(self, ransomNote, magazine):
if set(ransomNote) <= set(magazine):
for i in set(ransomNote):
if ransomNote.count(i) <= magazine.count(i):
pass
else:
return False
return True
return False
Feedback:
Runtime: 61 ms, faster than 75.10% of Python3 online submissions for Ransom Note.
Memory Usage: 14.1 MB, less than 82.56% of Python3 online submissions for Ransom Note.
class Solution:
def canConstruct(self, ransomNote, magazine):
for i in set(ransomNote):
if ransomNote.count(i) > magazine.count(i):
return False
return True
Feedback:
Runtime: 37 ms, faster than 96.08% of Python3 online submissions for Ransom Note.
Memory Usage: 14.1 MB, less than 82.56% of Python3 online submissions for Ransom Note.
242. Valid Anagram
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
class Solution:
def isAnagram(self, s, t):
m1, m2 = {}, {}
for i in set(s):
m1[i] = s.count(i)
for j in set(t):
m2[j] = t.count(j)
return m1 == m2
Feedback:
Runtime: 36 ms, faster than 97.63% of Python3 online submissions for Valid Anagram.
Memory Usage: 14.5 MB, less than 77.52% of Python3 online submissions for Valid Anagram.
To be continued... : )