-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ3_LongestSubstring_OptimizedSolution.java
More file actions
64 lines (52 loc) · 1.56 KB
/
Q3_LongestSubstring_OptimizedSolution.java
File metadata and controls
64 lines (52 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.gyanblog.leetcode;
import java.util.HashSet;
import java.util.Set;
/**
* Leetcode problem-3
* Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Example 2:
Input: "bbbbb"
Output: 1
Example 3:
Input: "pwwkew"
Output: 3
For explanation see: https://www.gyanblog.com/gyan/coding-interview/leetcode-solution-longest-substring-without-repeating/
*/
public class Q3_LongestSubstring_OptimizedSolution {
private String str;
public Q3_LongestSubstring_OptimizedSolution(String str) {
this.str = str;
}
public String getResult() {
int l = this.str.length();
Set<Character> set = new HashSet<>();
int i=0;
int j=0;
String maxStr = "";
while (i < l && j < l) {
if (!set.contains(this.str.charAt(j))) {
set.add(this.str.charAt(j));
j++;
String s = this.str.substring(i, j);
if (s.length() > maxStr.length()) {
maxStr = s;
}
}
else {
set.remove(this.str.charAt(i));
i++;
}
}
return maxStr;
}
public static void main(String[] args) {
String str = "pwwkew";
Q3_LongestSubstring_OptimizedSolution ss = new Q3_LongestSubstring_OptimizedSolution(str);
String result = ss.getResult();
System.out.println("Longest substring without repeating chars: " + result);
System.out.println("Length: " + result.length());
}
}