|
| 1 | +import java.util.List; |
| 2 | +import java.util.Set; |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashSet; |
| 5 | + |
| 6 | +/** |
| 7 | +Given a string s, find the length of the longest |
| 8 | +substring without repeating characters. |
| 9 | + |
| 10 | +Example 1: |
| 11 | +Input: s = "abcabcbb" |
| 12 | +Output: 3 |
| 13 | +Explanation: The answer is "abc", with the length of 3. |
| 14 | +Example 2: |
| 15 | +
|
| 16 | +Input: s = "bbbbb" |
| 17 | +Output: 1 |
| 18 | +Explanation: The answer is "b", with the length of 1. |
| 19 | +Example 3: |
| 20 | +
|
| 21 | +Input: s = "pwwkew" |
| 22 | +Output: 3 |
| 23 | +Explanation: The answer is "wke", with the length of 3. |
| 24 | +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. |
| 25 | + |
| 26 | +
|
| 27 | +Constraints: |
| 28 | +
|
| 29 | +0 <= s.length <= 5 * 104 |
| 30 | +s consists of English letters, digits, symbols and spaces. |
| 31 | + */ |
| 32 | +public class LengthOfLongestSubstring { |
| 33 | + public static void main(String[] args) { |
| 34 | + String s1 = "abcabcbb"; |
| 35 | + String s2 = "pwwkew"; |
| 36 | + String s3 = "au"; |
| 37 | + String s4 = "dvdf"; |
| 38 | + String s5 = " "; |
| 39 | + String s6 = "bpfbhmipx"; |
| 40 | + int longestString = lengthOfLongestSubstring(s6); |
| 41 | + System.out.println(longestString); |
| 42 | + } |
| 43 | + public static int lengthOfLongestSubstring(String s) { |
| 44 | + int stringLen = 0; |
| 45 | + String chars = new String(); |
| 46 | + |
| 47 | + for (int index = 0; index < s.length(); index++) { |
| 48 | + char c = s.charAt(index); |
| 49 | + if(chars.contains(String.valueOf(c))) { |
| 50 | + String newChars = new String(); |
| 51 | + for (int i=chars.length() - 1; i >=0; i--) { |
| 52 | + char pchar = chars.charAt(i); |
| 53 | + if(pchar != c) { |
| 54 | + newChars = String.valueOf(pchar) + newChars; |
| 55 | + } else { |
| 56 | + chars = newChars; |
| 57 | + break; |
| 58 | + } |
| 59 | + } |
| 60 | + chars = chars + String.valueOf(c); |
| 61 | + } else { |
| 62 | + chars = chars + String.valueOf(c); |
| 63 | + } |
| 64 | + if(stringLen < chars.length()) { |
| 65 | + stringLen = chars.length(); |
| 66 | + } |
| 67 | + } |
| 68 | + return stringLen; |
| 69 | + } |
| 70 | +} |
0 commit comments