生活随笔
收集整理的這篇文章主要介紹了
无重复字符最长子串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
無重復字符最長子串
雙指針/滑動窗口/移動隊列
無重復字符最長子串
package cn
.com
.codingce
.aaclengthoflongestsubstring
;import java
.util
.Arrays
;
import java
.util
.HashMap
;
import java
.util
.HashSet
;
import java
.util
.Map
;
import java
.util
.Set
;
import java
.util
.stream
.Collectors
;
public class LengthOfLongestSubstring {public static void main(String
[] args
) {int[] nums
= new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};int[] nums2
= new int[]{3, 2, 4};System
.out
.println(binarySearch(nums
, 5));System
.out
.println();Arrays
.stream(twoNumAdd(nums
, 6)).boxed().collect(Collectors
.toList()).forEach(num
-> System
.out
.print(num
));System
.out
.println();System
.out
.println(lengthOfLongestSubstringOne("aabscssd"));System
.out
.println(lengthOfLongestSubstring("aabscssd"));}public static int lengthOfLongestSubstring(String s
) {int length
= s
.length();if (length
< 2) return length
;Map
<Character, Integer> map
= new HashMap<>();char[] array
= s
.toCharArray();int size
= 0;int left
= 0;for (int right
= 0; right
< length
; right
++) {if (map
.containsKey(array
[right
])) {left
= Math
.max(map
.get(array
[right
]) + 1, left
);}map
.put(array
[right
], right
);size
= Math
.max(size
, right
- left
+ 1);}return size
;}public static int lengthOfLongestSubstringOne(String s
) {if (s
== null
|| s
.length() < 1) {return 0;}char[] chars
= s
.toCharArray();int size
= 0;for (int i
= 0; i
< chars
.length
; i
++) {Set
<Character> set
= new HashSet<>();for (int j
= i
; j
< chars
.length
; j
++) {if (set
.contains(chars
[j
])) {break;}set
.add(chars
[j
]);size
= set
.size() > size
? set
.size() : size
;}}return size
;}
二分查找
public static int binarySearch(int[] nums
, int target
) {int left
= 0, right
= nums
.length
- 1, mid
= 0;while (left
<= right
) {mid
= (left
+ right
) / 2;if (nums
[mid
] < target
) {left
= mid
+ 1;} else if (nums
[mid
] > target
) {right
= mid
- 1;} else {return mid
;}}throw new IllegalArgumentException("沒有目標值");}
兩數之和
public static int[] twoNumAdd(int[] nums
, int target
) {int left
= 0;int right
= nums
.length
- 1;while (left
< right
) {if (nums
[left
] + nums
[right
] > target
) {right
-= 1;} else if (nums
[left
] + nums
[right
] < target
) {left
+= 1;} else {return new int[]{left
, right
};}}throw new IllegalArgumentException("No two sum solution");}
}
總結
以上是生活随笔為你收集整理的无重复字符最长子串的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。