Leetcode Two Sum (java) Longest Substring Without Repeating Characters, leetcoderepeating

Source: Internet
Author: User

Leetcode Two Sum (java) Longest Substring Without Repeating Characters, leetcoderepeating

Solution 1:

Class Solution {public int lengthOfLongestSubstring (String s) {int max = 0; if (s. length () <= 1) {max = s. length (); return max;} for (int I = 0; I <s. length (); I ++) {// create a StringBuilder to store the temporary string StringBuilder str = new StringBuilder (); str. append (String. valueOf (s. charAt (I); // determines the length of each string for (int j = I + 1; j <s. length (); j ++) {// when the same string appears, stop matching and jump out of if (str. indexOf (String. valueOf (s. charAt (j) =-1) {str. append (String. valueOf (s. charAt (j);} else {break;} // The maximum record length if (str. length ()> max) {max = str. length () ;}} return max ;}}

This solution uses the Brute Force algorithm, that is, Brute Force search matching, with high time complexity.

 

Solution 2:

Class Solution {public int lengthOfLongestSubstring (String s) {int max = 0; // store the position of each Character Hashtable <Character, Integer> map = new Hashtable <Character, integer> (); // traverses the string for (int I = 0, j = 0; I <s. length (); I ++) {// change the position of the Left Border of the window and record the length of the window if (map. containsKey (s. charAt (I) {j = Math. max (map. get (s. charAt (I) + 1, j);} max = Math. max (max, I-j + 1); map. put (s. charAt (I), I);} return max ;}}

The idea of this solution is to calculate the length of two identical characters. It is like stretching the right border of a string to the right as a window. If the right border encounters an existing character in the window, then, the left border is stretched to the right of an existing character in the window, with low time complexity.


Github address: https://github.com/CyanChan/leetcode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.