File tree Expand file tree Collapse file tree
src/main/java/com/chen/algorithm/znn/string/test3 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 33import org .junit .Test ;
44
55import java .util .HashMap ;
6- import java .util .HashSet ;
76import 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/
3129 */
3230public 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}
You can’t perform that action at this time.
0 commit comments