I am trying to compare and see if a particular character exists in the string, but when i try to access the character which is in another string, its throws an error 'argument of type 'int' is not iterable'. How do i access the character from a string without causing the error?
def lengthOfLongestSubstring(self, s: str) -> int:
longStrLen = 0
totalStrLen = len(s)
holderString = ""
holderString += s[0]
longStrLen = 0
for i in range(1,totalStrLen-1):
if s[i] not in holderString:
holderString += s[i]
else:
if longStrLen < len(holderString):
longStrLen = len(holderString)
holderString = 0
return longStrLen
TypeError: argument of type 'int' is not iterable at Line
if s[i] not in holderString:
Your problem is on this line:
holderString = 0
You reassigned the holderString
variable to the integer 0. While strings can be iterated over, integers cannot. You attempt to iterate over the new integer on this line:
if s[i] not in holderString:
which causes the error.
There is a much better way to approach a function that returns the first repeated character though. Simply use the index()
method:
def findChar(char, string):
for c in string:
if c == char:
return string.index(c)
It appears you only need to count unique characters until you find the first duplicate. You can do that with a set.
def longest_substring(s: str) -> int:
seen = set()
for c in s:
if c in seen:
break
seen.add(c)
return len(seen)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.