class Solution {
public int lengthOfLongestSubstring(String s) {
String sub = "";
String longest = "";
for(int i = 0; i < s.length(); i++) {
if(sub.contains(s.charAt(i))) { //THIS LINE OF CODE PERTAINS TO MY QUESTION
if(sub.length() > longest.length()) {
longest = sub;
}
sub = s.charAt(i) + "";
} else {
sub += s.charAt(i);
}
}
return longest.length();
}
}
In the code above, why am I getting an error in the if statement that I have commented? I want to see if a certain character exists in a string. i.e, does a certain letter exist in the string.
A fix I found was to rewrite the if statement as -
if(sub.indexOf(s.charAt(i)) != -1) {
But I am genuinely not sure why we can't see if a specific character is present in a string or not with the contains method.