leetcode bug free
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"
分析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 }
分析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.
分析: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 }
以上是关于leetcode bug free的主要内容,如果未能解决你的问题,请参考以下文章
SDG精读与代码复现More Control for Free Image Synthesis with Semantic Diffusion GuidanceSDG