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