首页 > 代码库 > leetcode bug free

leetcode bug free

---倒序查看,不包含jiuzhang ladders中出现过的题。

 

2 Longest Palindromic Substring --- NOT BUG FREE

技术分享
求一个字符串中的最长回文子串。

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"
View Code

分析1:中心扩展,以每个字符为中心向外扩展,找到最长回文串。时间复杂度O(n^2),空间复杂度O(1)。

技术分享
 1 public class Solution {
 2     public String longestPalindrome(String s) {
 3         int length = 0;
 4         String res = "";
 5         
 6         //要考虑回文串是abba和aba两种情况
 7         for (int i = 0; i < 2 * s.length() - 1; i++) {
 8             int p1 = i % 2 == 0 ? i / 2 - 1 : i / 2;
 9             int p2 = i % 2 == 0 ? i / 2 + 1 : i / 2 + 1;
10             int len = i % 2 == 0 ? 1 : 0;
11             while (p1 >= 0 && p2 < s.length() && s.charAt(p1) == s.charAt(p2)) {
12                 len += 2;
13                 p1--;
14                 p2++;
15             }
16             if (len > length) {
17                 length = len;
18                 res = s.substring(p1 + 1, p2);
19             }
20         }
21         return res;
22     }
23 }
View Code

分析2:Manacher算法。时间复杂度O(n),空间复杂度O(1)。

 

 

1 Longest Substring Without Repeating Characters --- not bug free

技术分享
给一个字符串,找出其中不包含重复字符的最长子串的长度。

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
View Code

分析:hash表记录每个字符最近出现的索引,p1指针表示以当前字符为末尾的最长不重复子串的左端点。时间复杂度O(n)。

技术分享
 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         Map<Character, Integer> map = new HashMap<Character, Integer>();
 4         int res = 0;
 5         int p1 = 0;
 6         int p2 = 0;
 7         
 8         for (; p2 < s.length(); p2++) {
 9             char c = s.charAt(p2);
10             if (map.containsKey(c) && p1 <= map.get(c)) {
11                 p1 = map.get(c) + 1;
12             } 
13             map.put(c, p2);
14             res = Math.max(res, p2 - p1 + 1);
15         }
16         return res;
17     }
18 }
View Code

 

leetcode bug free