Skip to content

Commit 149e13c

Browse files
author
chenweijie
committed
string
1 parent 46ec69b commit 149e13c

1 file changed

Lines changed: 33 additions & 2 deletions

File tree

‎src/main/java/com/chen/algorithm/znn/string/test3/Solution.java‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
import org.junit.Test;
44

55
import java.util.HashMap;
6-
import java.util.HashSet;
76
import java.util.Map;
8-
import java.util.Set;
97

108
/**
119
* https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/hua-jie-suan-fa-3-wu-zhong-fu-zi-fu-de-zui-chang-z/
@@ -31,6 +29,11 @@
3129
*/
3230
public class Solution {
3331

32+
/**
33+
* 返回子串长度
34+
* @param s
35+
* @return
36+
*/
3437
public int lengthOfLongestSubstring(String s) {
3538
if (s == null || s.length() == 0) {
3639
return 0;
@@ -52,10 +55,38 @@ public int lengthOfLongestSubstring(String s) {
5255
return ans;
5356
}
5457

58+
/**
59+
* 返回子串
60+
* @param s
61+
* @return
62+
*/
63+
public String getSubString(String s) {
64+
if (s == null || s.length() == 0) {
65+
return s;
66+
}
67+
Map<Character, Integer> map = new HashMap<>();
68+
int start = 0;
69+
String sub = "";
70+
for (int end = 0; end < s.length(); end++) {
71+
char c = s.charAt(end);
72+
if (map.containsKey(c)) {
73+
start = Math.max(start, map.get(c));
74+
}
75+
76+
if (sub.length() < end - start + 1) {
77+
sub = s.substring(start, end + 1);
78+
}
79+
map.put(c, end + 1);
80+
}
81+
return sub;
82+
}
83+
5584
@Test
5685
public void test() {
5786
System.out.println(lengthOfLongestSubstring("abcabcbb"));
5887
System.out.println(lengthOfLongestSubstring("bbbbb"));
5988
System.out.println(lengthOfLongestSubstring("pwwkew"));
89+
System.out.println(getSubString("pwwkew"));
90+
6091
}
6192
}

0 commit comments

Comments
 (0)