LeetCode Exercise In Java - Longest Substring Without Repeating Characters - FAST Solution

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ก.ย. 2024

ความคิดเห็น • 186

  • @CodingWithJohn
    @CodingWithJohn  2 ปีที่แล้ว +15

    Thanks to Mailgun for sponsoring this video! Head to mailgun.com/john to try Mailgun free today.
    Looking forward to seeing how you guys make this solution even better!

    • @aryansanojraj6618
      @aryansanojraj6618 2 ปีที่แล้ว +1

      Can you let us know the compiler you use for the videos?

    • @ripanpramanick425
      @ripanpramanick425 ปีที่แล้ว +1

      Not able to understand how this algo will work for some string like "abcdcga" as we will keep our left pointer at first a and we will increment right pointer, at when right pointer at second c it will get repeated letter and will increment left pointer to b and in next iteration it will move to g and will register length of bcdcg but this substring is already having repeated character. Rather than incrementing left pointer by one we should increment it by lastCharOccuredIndex+1

    • @ZelenoJabko
      @ZelenoJabko 3 หลายเดือนก่อน

      The complexity of your first algorithm is n cubed, not n squared! There is one more loop hidden in String.indexOf, looking for a duplicate character.

  • @playtopgames3261
    @playtopgames3261 2 ปีที่แล้ว +70

    Best java chanel on TH-cam

  • @nahomg6945
    @nahomg6945 2 ปีที่แล้ว +55

    You genuinely have one of the best programming explanation videos on this site, honestly. Funny, I was discussing learning about the Sliding Window algorithm to practice Leetcode questions with a friend yesterday, and lo and behold you've uploaded a great explanation literally 24hrs later, legendary! Could you please upload more Leetcode explanation questions? If not on TH-cam, perhaps a course?

    • @Achraf_0101
      @Achraf_0101 5 หลายเดือนก่อน

      i already signed up in his course but it does not contain any exercises i wonder if there is another course where he solves problems

    • @joydeep_
      @joydeep_ 3 หลายเดือนก่อน

      Same feelings here, we need more leet code problems...

  • @jayshreebargohil
    @jayshreebargohil 2 ปีที่แล้ว +13

    I had just solved this problem and found this video. You explained each solution and your approach in the best way. Your way to explaining make things crystal clear John !!

  • @vijal-patel
    @vijal-patel 2 ปีที่แล้ว +25

    please keep doing these, your explanations are so much more in depth than other youtube channels

  • @thomas_m3092
    @thomas_m3092 ปีที่แล้ว +7

    John, you are a wizard. Everythings looks so logical and simple. Please make more videos like this.

  • @tund_101_hd9
    @tund_101_hd9 2 ปีที่แล้ว +5

    This is probably one of the best tutorials out there and i think TH-cam is with me in this.❤️ I could you not, even though I have watched it already it is every time the first video in my recommended 😂
    Guess I'll watch it twice. Keep up the good work!

  • @claytonalmeida6046
    @claytonalmeida6046 2 ปีที่แล้ว +14

    Would love to watch a complete java dsa course from you

    • @jayshreebargohil
      @jayshreebargohil 2 ปีที่แล้ว

      DSA would be more easy and interesting with John 😀

  • @tiagocarvalho4119
    @tiagocarvalho4119 ปีที่แล้ว +7

    You have to be careful when using a MAP to lookup something because, even though its O(1) in time complexity, there is a lot of overhead. Let's say that the constant time for a lookup in a MAP is always 500 nanoseconds, if the indexOf (that has a time complexity of O(n)) takes only 300 nanoseconds because it finds the answer in the first few characters, then the indexOf will perform better. This obviously can be measured and we can come up with some threshold that tells us what algorithm to use in each situation. My guess is that in the English language indexOf will always perform better because we are dealing with words that are small in size (there is always the repeating space character).

    • @Phl3xable
      @Phl3xable ปีที่แล้ว

      My thoughts exactly

  • @minakianrad812
    @minakianrad812 ปีที่แล้ว +3

    An excellent in-depth explanation of two approaches to solving this problem. Thank you very much, John.

  • @rushio8673
    @rushio8673 ปีที่แล้ว +2

    Great job, please keep posting the leetcode solution videos in structural manner(for eg top 50 that includes most practices/datastructures) , this helps a lot in preparing for interviews.

  • @MTB_Bay_Area
    @MTB_Bay_Area 2 ปีที่แล้ว +2

    For the brute force solution. I suggest checking if the max need to be updated in the "if contains part" that makes sure that we only do it right before we break. It is one time per substring. We fount a substring, now, let's check if it is better than the other we had so far. Second, I will suggest using HashSet instead of StringBuilder. HashSet has contains method and it is faster.

  • @yasasmaddumage
    @yasasmaddumage 2 ปีที่แล้ว +5

    I love this series. Thank you...

  • @SimoLPers
    @SimoLPers ปีที่แล้ว +1

    I'm currently just at the brute-force method in the video, but for the lookups I'd probably use a hashset.
    I would therefore prevent an O(n²) lookup.
    But the brute-force method was the first idea for me as well.

  • @whiz-code
    @whiz-code ปีที่แล้ว

    You are really a coding geek. Even the concepts known, still visit them and keep something. Your explanations are far reaching. Thank you.

  • @lanatimmo3686
    @lanatimmo3686 ปีที่แล้ว +4

    It's great! Please, do more Leetcode Exercise explanations!🙏

  • @SimanAndGarfunkel
    @SimanAndGarfunkel 7 หลายเดือนก่อน

    I love the final thoughts on the differences of performance between the 2 last algorithms, answered all the questions I had to myself. Thnak you!

  • @Michaelpschreib
    @Michaelpschreib 8 หลายเดือนก่อน

    I appreciate that you go into the brute force solution and also the more clever solution. Thanks for these!!

  • @gauravmehta6831
    @gauravmehta6831 2 หลายเดือนก่อน

    A unique way of explanation, clear concise.

  • @benjaminandersonii9842
    @benjaminandersonii9842 ปีที่แล้ว +3

    The reason for the final solution being faster is because while hash tables have "constant" lookup time it still takes time. Depending on the hashing function and the initial size of the hashmap the lookup, add, and resize functions may be more time consuming than just linearly looking through an array of characters. Especially if the hashing function has division, because of how bad computers are at it. So rather than your hashmap having O(1) time complexity for lookup its probably more like O(100) which is potentially smaller than the size of n.
    Sorry for the long rambling answer, but yeah hashmaps are great, if you know how the data is being put into them. They also take up a *bunch* of space, so finding an algorithm that is similar in functionality, but doesn't use them is always the way to go.

    • @vedantjha2327
      @vedantjha2327 ปีที่แล้ว

      True, just to add your answer, hashmap has constant time complexity in average case, but O(n) in worst case. So it's not 100% perfect n effective in all cases

  • @jordanT_alker
    @jordanT_alker 4 หลายเดือนก่อน

    Interesting!
    I am very honest with myself, I am not seeing the full picture when it occurs to recursion;
    However, I did grasp the idea of the "quicksort" method a bit better, not 100% but we are learning.
    I can see this is almost similar to an array.

  • @liamoua9192
    @liamoua9192 ปีที่แล้ว

    John, you’ve helped me understand DS&A in Java better than before. The way you explained things are easy to understand and follow. I’m a visual learner and your explanations makes it easier for me visualize & understand. Thank you and please keep these leet code videos coming. Your other videos on Java has truly helped me understand Java so much more than my professors lol you are incredible in the work that you’re doing for me and many. We cannot thank you enough ❤ I appreciate you.

    • @CodingWithJohn
      @CodingWithJohn  ปีที่แล้ว

      Thanks so much for the very kind words!

    • @91-ritikjain36
      @91-ritikjain36 11 หลายเดือนก่อน

      when we get full playlist of leetcode in java you are amazing i am from india @@CodingWithJohn

  • @foratzoabi1311
    @foratzoabi1311 8 หลายเดือนก่อน

    Hey John! First of all thanks for the amazing video!
    Short answer for why indexOf is faster in this case:
    It is simply because in this case it has an O(1) runtime, how? here is how:
    Before you slide your right pointer to the right you have already made sure that this substring has different characters, which in the worst case will be 24 characters long. Since you know it will never be longer than 24 characters, or 34 if numbers are included in the string, then it is constant time, because no matter how big your string will be, it will be in the worst case that maximum substring :D so it is related to the valid substring and not to the input! :D
    And since the map indeed has access and write time of O(1) it still has an overhead for hash calculation and storing and etc... which take more operations / time than indexOf in that case, but since none of them is related to n, the one with the shorter/faster operations wins :D
    I hope that was helpful!

  • @Verdarin
    @Verdarin ปีที่แล้ว +1

    I know this is a bit late, but I believe Map is quite slow in runtime from what I heard and so it doesnt give off the best speed, Map is a great to use if you dont care much about speed as much as you want cleaner and simple code (tho run time is and should be priority)

  • @zerkinanastya4410
    @zerkinanastya4410 ปีที่แล้ว

    Definitely one of the best explanations or just the best, starting from the basic one (brute force) just to kick off and let viewers like me grasp the idea before jumping to more complex solutions. Thank you!

  • @EdgarRamirez-ry2je
    @EdgarRamirez-ry2je 11 หลายเดือนก่อน

    More videos like this with solutions for diferent letcode, hackerank problems this is very much usefull to improve skills, you explain as a master

  • @germimonte
    @germimonte 2 ปีที่แล้ว +8

    given that there's a finite and constant number of letters, you could probably replace the HashMap with a regular array for a negligible decrease in time and memory

    • @CodingWithJohn
      @CodingWithJohn  2 ปีที่แล้ว +6

      Yeah it could be the case that despite the technical time complexity being lower, because n will never be more than 50,000, simple sequential array searches might just be more performant

    • @cipherxen2
      @cipherxen2 2 ปีที่แล้ว +4

      @@CodingWithJohn you don't need array of 50000 elements, just 255 for ASCII characters

    • @bhaskarpurkayastha485
      @bhaskarpurkayastha485 2 ปีที่แล้ว +1

      @@cipherxen2 and a character can be found in this array in O(1) time by -
      int lastEncountered = charIndexes[currentChar]; Initialize charIndexes[255] with all -1;

  • @rahulg1715
    @rahulg1715 6 หลายเดือนก่อน

    At 35:00 we should use indexOfFirstAppearenceInsubstring

  • @logesh9141
    @logesh9141 2 ปีที่แล้ว +1

    hi John,
    The way of explanation which you are giving is excellent.
    Since, I am mostly working JAVA. You videos are very mich helpful for me to achieve greater heights in my life.
    I mostly use ECLIPSE for my Java Projects. If possible please guide me in using Intellij with each and every shortcuts.
    Thanks in Advance,
    Logesh

  • @nicovogel9924
    @nicovogel9924 2 ปีที่แล้ว +2

    I would never thought of HashMap is it possible to do the same thing with a list just if list.contains(a) list.remove(a) list.append(a). Could you pls make a video about how fast all these datastructures in comparison are.
    you can explain very good :)

  • @Shivam-gh2mq
    @Shivam-gh2mq ปีที่แล้ว

    I watched till 25:32 and was able to come up with a solution. Thanks for this amazing explanation!

  • @zainahmed755
    @zainahmed755 ปีที่แล้ว +1

    Best channel ever ! , please keep going with the leatcode series

  • @zoflax
    @zoflax 2 ปีที่แล้ว +1

    this series is actually so good.

  • @Asingh42
    @Asingh42 3 วันที่ผ่านมา

    I tried a better idea to use a fixed size array for character mapping it got more optimised thanks for the video need more leetcode content

  • @markmuyot2436
    @markmuyot2436 6 หลายเดือนก่อน

    I liked your videos, you made them all easy to grasp! please do more leetcodes tutorials and data structures and algorithms content

  • @saeednoshadi3922
    @saeednoshadi3922 ปีที่แล้ว +1

    This playlist is amazing, Why don't you continue this series of videos?

  • @sankalp.m.patilsmp1472
    @sankalp.m.patilsmp1472 2 ปีที่แล้ว +1

    this channel has wonderful content, and easy to understand explaination.

  • @kafychannel
    @kafychannel ปีที่แล้ว +1

    Great explanation,thank you !

  • @xeanluxcrille6847
    @xeanluxcrille6847 2 ปีที่แล้ว +2

    I'm not entirely sure, but the answer to the difference in time complexity might be in how indexOf is implemented in the first place. I'm not an expert at all, but what if the indexOf method itself already utilizes the exact same Map implementation? Meaning, your Map implementation could be a duplicate of indexOf(), except indexOf() doesn't have the extra steps within the implementations of contains() and get() because it's already encapsulated in core Java. I'm just guessing here, of course. Pretty sure I could be wrong.

  • @rishiraj2548
    @rishiraj2548 2 ปีที่แล้ว +3

    Name of Map:
    seenChars

  • @bekuostudio
    @bekuostudio 10 หลายเดือนก่อน

    Thanks for the clear explanation. I'm struggling with tech interviews. How am I supposed to complete a challenge in a short time? I just got stuck in the last one. I'm trying so hard to understand. I've been practicing LeetCode exercises, but there's always something tricky, and I've never seen anything similar before. It's so frustrating

  • @markmuyot2436
    @markmuyot2436 11 หลายเดือนก่อน

    Hi John I like how you present your leetcode solutions, so easy to follow and understand. Hope to see more of this or if you have anothe platform teaching leetcode problems , I would be happy to know.. Thank you

  • @psg9278
    @psg9278 2 ปีที่แล้ว +1

    Thanks Please do more

  • @deepakroy3476
    @deepakroy3476 7 หลายเดือนก่อน

    You make programming easy and simple

  • @otisopoku37
    @otisopoku37 9 หลายเดือนก่อน

    Your explanations are very good. More leetcode!!!!!!!!!

  • @laharibasu9731
    @laharibasu9731 ปีที่แล้ว

    Can you please make more of these leetcode java solutions videos. They are of great help and you make us understand wonderfully.

  • @swagatpandak7325
    @swagatpandak7325 2 ปีที่แล้ว +1

    Continue this series in java please.Thanks john.

    • @CostaKazistov
      @CostaKazistov 2 ปีที่แล้ว

      Yes, please!
      Most LeetCode videos out there are either Python or C++
      Definitely want to see more LeetCode walkthroughs in Java (or Kotlin)

  • @odaia.7519
    @odaia.7519 ปีที่แล้ว +1

    I think maps are very performant in java, so it's not because of the map functions. What i think it's because of initialize an object of it and this takes time. I saw this while measuring a function using map in my performance project.

  • @dadaboymasharipov2653
    @dadaboymasharipov2653 2 ปีที่แล้ว +1

    Hi there!! I really like your videos so much you make them easy to understand!! I want to ask you something can you recommend a book or books to improve our problem solving skill and to learn data structures

  • @jonathanhawkins9147
    @jonathanhawkins9147 2 ปีที่แล้ว

    Yum just a subscriber with the initial sponsor ad

  • @ashashankar29
    @ashashankar29 ปีที่แล้ว

    Excellent explanation and solution. I clearly understood the problem and solution. thank you

  • @ArunKumar-jk5pq
    @ArunKumar-jk5pq 2 ปีที่แล้ว

    This is awesome way of teaching! Thanks John!

  • @diegosuarezgarcia248
    @diegosuarezgarcia248 ปีที่แล้ว +1

    I'm assuming this last approach is faster because the window defined by 'left' and 'right' never ends up being long enough to operate less efficiently than when using a map. I mean, Imagine the 5*10^4 (50000) String where ALL its characters are different (this means, maxLength would be 50000). Everytime you call 'indexOf()', Java is basically running a O(N) algorithm, where N is the length of the window we use. Said window starts with length 0, it's increased each loop and its length ends up being 50000. We have a complexity O(50000!), don't we? For this kind of scenario, unless I am mistaken, using a map is a way better choice.

    • @toby9999
      @toby9999 หลายเดือนก่อน +1

      If we're limited to the ASCII character set, then the maximum length will be < 128.

    • @diegosuarezgarcia248
      @diegosuarezgarcia248 หลายเดือนก่อน

      @@toby9999 fair enough

  • @germimonte
    @germimonte 2 ปีที่แล้ว +1

    as for the better time, my best guess is a combination of the sample data and the relatively massive overhead of the default HashMap implementation, using arrays to implement your own map SHOULD in theory produce better results, I'll test it later. Or you could just pass 127 as the initial capacity of the map?

  • @bendror8302
    @bendror8302 ปีที่แล้ว

    Nice to learn from you John, can you add more solutions from LeetCode?

  • @VinuCP
    @VinuCP ปีที่แล้ว

    Thanks John for awesome video and great explanation. For the Map solution wouldn't it also help to add an exit condition to break the loop
    if (maxLength > input.length() - right + 1) - so we need not iterate the remaining characters in the input.

  • @Tibetan-experience
    @Tibetan-experience 2 ปีที่แล้ว

    Thanks John. Always putting these awesome videos.

  • @benignexistence4558
    @benignexistence4558 12 วันที่ผ่านมา

    it's crazy to see that last solution. i am watching this after submitting my solution, which is almost identical. however, i didn't know you can set the start index of String.indexOf(), so I had a String t that was set to s.substring(left, right) every loop and String c that was set to s.charAt(right). I then had the left pointer move by using ```left = (t.contains(c)) ? left + t.indexOf(c) + 1 : left;``` lmao. Funny enough, it gave the exact same time of 5ms, but their version uses a bit less space (mine used 44.94MB)

  • @antonignatenko7776
    @antonignatenko7776 2 ปีที่แล้ว

    if possible more videos like this, especially interested in thought process behind solutioon

  • @rcciit9226
    @rcciit9226 ปีที่แล้ว

    Wow so easy to learn and understand , you have a new student sir.

  • @yedum321
    @yedum321 2 ปีที่แล้ว

    I've been binging your videos. I feel like God sent you to me. Thank you

  • @DominikGuzowski
    @DominikGuzowski ปีที่แล้ว

    The second solution is definitely better than the first one than the map purely because our domain is so small, so all of the map operations while "constant" probably take a tad bit longer than this linear search, but again this is just due to the domain. If this was not strings but instead an array of numbers, where the domain can be much larger, the map would probably outperform this approach, though that is just a guess.

  • @MTB_Bay_Area
    @MTB_Bay_Area 2 ปีที่แล้ว

    for the version that uses the HashMap, I would suggest to have an else. when we are in the "if contains" we are always shortening the substring and hence no need to update the max.

  • @rameezalam1968
    @rameezalam1968 ปีที่แล้ว

    Hi Johnny sin, good to see in as a software developer role as well

  • @NiChOlAs-gw7iw
    @NiChOlAs-gw7iw ปีที่แล้ว

    wow pls, do more Leetcode exercise explanations!

  • @arthurmagamedov3179
    @arthurmagamedov3179 ปีที่แล้ว

    Thanks John for the amazing video!! As for maps - what is the low level implementation of maps in JVM code? I mean, does it calculate the hash for the key when put or get methods are invoked? If it does, then adding or reading keys will be quite expensive , and explains why indexOf works faster.

  • @james-ansley
    @james-ansley 2 ปีที่แล้ว

    The max possible substring is bounded by the number of possible characters in the string, m, which given the problem constraints seems to be at most ~100ish. And, I would imagine on average the actual distance between the left and right pointers will be much less than this. This then means you are *effectively* comparing two linear solutions (even though the indexOf solution is technically nm - m is small).
    I would imagine that for small values of m the simplicity of linearly looping through a few characters of a string would be much faster than map lookups and manipulation. It would be interesting to see if the map-based solution would surpass the indexOf solution by increasing m, by, for example, using all UTF-8 chars.

    • @CodingWithJohn
      @CodingWithJohn  2 ปีที่แล้ว +2

      Well the problem states that the input string may be up to 50,000 characters long. But I do think it's a good insight that the max length of the longest substring is bounded by the number of unique characters in the character set being used. In this case it says "English letters, digits, symbols and spaces." I'd have to add all those up to be sure, but let's say it's maybe 100, which may be a big reason the map solution is overkill at this level

  • @158thavashankarrajakc9
    @158thavashankarrajakc9 ปีที่แล้ว

    need more tutorials please :) thank you!

  • @ALEXGAYMAR2312
    @ALEXGAYMAR2312 ปีที่แล้ว

    Could you please do one about Polymorphic load/save methods for Java Io file handling

  • @bendror8302
    @bendror8302 ปีที่แล้ว +1

    wow thanks 🙏

  • @trae_brown
    @trae_brown 2 ปีที่แล้ว

    John could you solve this problem with an array list?

  • @pv2930
    @pv2930 ปีที่แล้ว

    Hi can u upload a video on leetcode 992 ?

  • @aamirshekh934
    @aamirshekh934 2 ปีที่แล้ว

    What are the java project that will be modern..Or i should have to learn other tech stack to make project to stand out??

  • @twokatana
    @twokatana 2 ปีที่แล้ว

    Great Video! But what book would you recommend for learning java?

  • @rupambhattacharyya780
    @rupambhattacharyya780 ปีที่แล้ว

    Long story short, here two algorithms are used ..1)sliding window algorithm of variable size
    2) 2 pointer approach

  • @sankalp.m.patilsmp1472
    @sankalp.m.patilsmp1472 2 ปีที่แล้ว

    can you please teach dynamic programming.

  • @mohammedal_mostafa805
    @mohammedal_mostafa805 2 ปีที่แล้ว

    I think when creating a string object that object knows where is each character's index and when we call indexOf method its return the index that object saves ,butt i am not sure couse i know indexOf method is leanar search

  • @sysybaba420
    @sysybaba420 11 หลายเดือนก่อน

    @31:42 -> is there a better way to find length of the substring(right - left + 1)? Can we do something like s.subString(left, right) and pass this as an argument to s.length() somehow and return the length of that substring? thoughts?

    • @sysybaba420
      @sysybaba420 11 หลายเดือนก่อน

      Also at 30:00 why not just do a left++?

  • @hasibulhasansiju
    @hasibulhasansiju ปีที่แล้ว

    Want more of this

    • @CodingWithJohn
      @CodingWithJohn  ปีที่แล้ว +1

      I'll definitely do more sometime soon!

  • @kybkap8686
    @kybkap8686 2 ปีที่แล้ว

    hey jhon can you make a video about event listeners. im trying to make a simple game where you move a star char inside a list with arrow keys.

  • @EdgarRamirez-ry2je
    @EdgarRamirez-ry2je 2 ปีที่แล้ว

    Make tutorias about algorithms DFS and BFS with Graphs

  • @alexanderkomanov4151
    @alexanderkomanov4151 ปีที่แล้ว

    AMAZING!

  • @Harsha._.
    @Harsha._. 2 ปีที่แล้ว

    Awesome best explanation 👏

  • @jatinkumar7287
    @jatinkumar7287 2 ปีที่แล้ว

    Thanks for this explaination🥰

  • @ananthukkumar987
    @ananthukkumar987 ปีที่แล้ว

    hi john I've a doubt over here, does using .toString or just +"" instead of String.valueOf makes any difference

  • @chinmayrath8494
    @chinmayrath8494 2 ปีที่แล้ว

    thanks for the video !!

  • @rishiraj2548
    @rishiraj2548 2 ปีที่แล้ว

    Thanks

  • @_Anna_Nass_
    @_Anna_Nass_ ปีที่แล้ว

    More leetcode problems!!! I like this style of video 🧌

  • @matteodidone9801
    @matteodidone9801 ปีที่แล้ว

    Is it just me, or "Coding With John" is the new "Alex Lee" when it comes to learning Java?

  • @jordanT_alker
    @jordanT_alker 4 หลายเดือนก่อน

    Hmm... lets see what we learn today!

  • @prakharjain-r6t
    @prakharjain-r6t หลายเดือนก่อน

    easiest explanation ever. search for 10 other videos. this is the easiest. thanks.

  • @georgesayoub6564
    @georgesayoub6564 ปีที่แล้ว

    BFS DFS next?

  • @RoysIdea
    @RoysIdea 2 ปีที่แล้ว

    substringCharacterIndex, but then you have to remove characters to left

  • @praveenpp2929
    @praveenpp2929 ปีที่แล้ว

    I used HashSet .... but i got 133 ms why do you think so ?

  • @larryd9577
    @larryd9577 ปีที่แล้ว

    Map lastSeenCharacterLoopup;

  • @bin_california
    @bin_california หลายเดือนก่อน

    Think of it this way: why there is no flight from San Jose to San Francisco?

  • @tarunsoni6971
    @tarunsoni6971 ปีที่แล้ว

    Joke: Our beloved Johnny sins was so good at Java I didn't know was used to watch him in incognito now without it as well indeed he can be anything.

  • @sef2000
    @sef2000 ปีที่แล้ว

    I think myMap is a perfect name

  • @pj1mb3970
    @pj1mb3970 8 หลายเดือนก่อน

    I coded this way using a map and still ended up solving in 5ms
    class Solution {
    public int lengthOfLongestSubstring(String s) {
    if (s == null || s.length() == 0) {
    return 0;
    }
    int maxLength = 0;
    int start = 0;
    HashMap charIndexMap = new HashMap();
    for (int end = 0; end < s.length(); end++) {
    char currentChar = s.charAt(end);
    if (charIndexMap.containsKey(currentChar)) {
    start = Math.max(start, charIndexMap.get(currentChar) + 1);
    }
    charIndexMap.put(currentChar, end);
    maxLength = Math.max(maxLength, end - start + 1);
    }
    return maxLength;
    }
    }

  • @cutechinmoy
    @cutechinmoy ปีที่แล้ว

    How about this solution.
    String s = "abcabcda";
    char[] cc = s.toCharArray();
    List stringList = new ArrayList();
    int len = 0;
    for(int i =0 ;i < s.length(); i++){
    char c = cc[i];

    if (!stringList.contains(c)) {
    System.out.println("Adding to List " + c);
    stringList.add(c);
    } else {
    if(stringList.size() > len) {
    len = stringList.size();

    stringList = new ArrayList();
    stringList.add(c);
    System.out.println("=======Reset List===== ");
    }
    }
    }
    System.out.println("Len "+len);