This is my code to find the length of the longest substring without repeating characters. Does this code run in O(n) time? Or does it run in O(n^2) time? I am not sure if the String methods run in O(n) time or O(1) time.
A test case includes: "pwwkewo" returning 4 because "kewo" is the the longest substring inside the string that has unique characters.
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
String sub = "";
for(int i=0; i<s.length(); i++) {
//add that char to the sub string
sub = sub + s.charAt(i);
//if we find a char in our string
if(sub.indexOf(s.charAt(i)) != -1) {
//drop any replicated indexes before it
sub = sub.substring(sub.indexOf(s.charAt(i)) + 1);
}
if(sub.length() > maxLength) {
maxLength = sub.length();
}
}
return maxLength;
}
sub.indexOf() can take linear time, since it might have to check all the characters of sub. And the length of sub is O(n) in the worst case (assuming your input has no repeating characters).
Therefore your total running time is O(n2), since the loop has n iterations and in each iteration you call indexOf().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With