leetcode
Java
substring
Given a string s, find the length of the longest substring without repeating characters.
找出字串s中沒有重複最長的子字串(substring)的長度
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
window
都往右移一格,並且判斷窗格內是否有與新加入的字元重複,如有重複將左邊指標left
往右刪除字元直到窗格內未有重複字元為止
max_len
會在移動窗格最後判斷目前合法的窗格長度是否大於原本的值這樣的寫法會使時間複雜度為
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null) return 0;
HashSet<Character> window = new HashSet<Character>();
int max_len = 0;
int left = 0;
int len = 0;
char[] ss = s.toCharArray();
for (int i = 0;i < s.length();i++){
while(window.contains(ss[i])){ //判斷是否有重複字元
window.remove(ss[left]);
left++; //指標因刪除往右一格
len--;
}
window.add(ss[i]);
len++;
if(max_len < len)
max_len = len;
}
return max_len;
}
}
Description Given a string s, return the longest palindromic substring in s. 給定一個String,並找出最長的回文子字串(palindromic substring),如有多個相同長度的最長子字串可只回傳一個 Example Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
Aug 18, 2021Description The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
Aug 18, 2021Description Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 將整數反轉,遇到超過32-bit的數就回傳0 Example Input: x = 123 Output: 321
Aug 15, 2021Description Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 給一字符串數組, 將錯位詞(指相同字符不同排列的字符串) 分組 Example Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Aug 15, 2021or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up