[关闭]
@Yano 2019-09-20T02:50:10.000000Z 字数 11342 阅读 3262

LeetCode String 题目汇总

LeetCode


公众号

coding 笔记、点滴记录,以后的文章也会同步到公众号(Coding Insight)中,希望大家关注^_^

https://github.com/LjyYano/Thinking_in_Java_MindMapping

3 Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

题目描述

Given a string, find the length of the longest substring without repeating characters.

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.

代码

  1. class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. int start = 0, end = 0, ans = 0;
  4. Set<Character> set = new HashSet<>();
  5. while (end < s.length()) {
  6. if (!set.contains(s.charAt(end))) {
  7. set.add(s.charAt(end++));
  8. ans = Math.max(ans, set.size());
  9. } else {
  10. set.remove(s.charAt(start++));
  11. }
  12. }
  13. return ans;
  14. }
  15. }

5 Longest Palindromic Substring

https://leetcode.com/problems/longest-palindromic-substring/

题目描述

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

代码

  1. class Solution {
  2. public String longestPalindrome(String s) {
  3. int pos = 0, ans = 0, p0 = 0, p1 = 0;
  4. while (pos < s.length()) {
  5. for (int i = 0; i <= 1; i++) {
  6. int start = pos, end = pos + i;
  7. while (start >= 0 && end < s.length()) {
  8. if (s.charAt(start) == s.charAt(end)) {
  9. start--;
  10. end++;
  11. } else {
  12. break;
  13. }
  14. }
  15. if (ans < end - start - 1) {
  16. ans = end - start - 1;
  17. p0 = start;
  18. p1 = end;
  19. }
  20. }
  21. pos++;
  22. }
  23. return s.substring(p0 + 1, p1);
  24. }
  25. }

8 String to Integer (atoi)

https://leetcode.com/problems/string-to-integer-atoi/

题目描述

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes:
It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

代码

  1. class Solution {
  2. public int myAtoi(String str) {
  3. if (str == null || str.length() == 0) {
  4. return 0;
  5. }
  6. char[] c = str.trim().toCharArray();
  7. int i = 0, flag = 1, ans = 0;
  8. if (c[i] == '+') {
  9. i++;
  10. } else if (c[i] == '-') {
  11. flag = -1;
  12. i++;
  13. }
  14. for (; i < c.length; i++) {
  15. if (c[i] > '9' || c[i] < '0') {
  16. break;
  17. }
  18. // 防止溢出
  19. if (ans > Integer.MAX_VALUE / 10
  20. || (ans == Integer.MAX_VALUE / 10 && (c[i] - '0') > Integer.MAX_VALUE % 10)) {
  21. return (flag == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
  22. }
  23. ans = ans * 10 + c[i] - '0';
  24. }
  25. return ans * flag;
  26. }
  27. }

17 Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

题目描述

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

代码

  1. class Solution {
  2. public List<String> letterCombinations(String digits) {
  3. List<String> ans = new ArrayList<>();
  4. if (digits == null || digits.length() == 0) {
  5. return ans;
  6. }
  7. List<String> list = Arrays.asList("", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz");
  8. robot(0, ans, list, "", digits);
  9. return ans;
  10. }
  11. private void robot(int start, List<String> ans, List<String> list, String tmp, String digits) {
  12. if (tmp.length() == digits.length()) {
  13. ans.add(tmp);
  14. return;
  15. }
  16. int num = digits.charAt(start) - '0';
  17. if (num > 1) {
  18. for (Character c : list.get(num - 1).toCharArray()) {
  19. robot(start + 1, ans, list, tmp + c, digits);
  20. }
  21. }
  22. }
  23. }

20 Valid Parentheses

https://leetcode.com/problems/valid-parentheses/

题目描述

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

代码

  1. class Solution {
  2. public boolean isValid(String s) {
  3. if (s == null || s.length() % 2 == 1) {
  4. return false;
  5. }
  6. Map<Character, Character> map = new HashMap<>();
  7. map.put('(', ')');
  8. map.put('[', ']');
  9. map.put('{', '}');
  10. Stack<Character> stack = new Stack<Character>();
  11. for (Character c : s.toCharArray()) {
  12. if (map.keySet().contains(c)) {
  13. stack.push(c);
  14. } else if (map.values().contains(c)) {
  15. if (!stack.empty() && map.get(stack.peek()) == c) {
  16. stack.pop();
  17. } else {
  18. return false;
  19. }
  20. }
  21. }
  22. return stack.empty();
  23. }
  24. }

22 Generate Parentheses

https://leetcode.com/problems/generate-parentheses/

题目描述

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

代码

  1. class Solution {
  2. public List<String> generateParenthesis(int n) {
  3. List<String> ans = new ArrayList<>();
  4. robot(0, 0, n, "", ans);
  5. return ans;
  6. }
  7. private void robot(int left, int right, int n, String tmp, List<String> ans) {
  8. if (tmp.length() == n * 2) {
  9. ans.add(tmp);
  10. return;
  11. }
  12. if (left < n) {
  13. robot(left + 1, right, n, tmp + "(", ans);
  14. }
  15. if (right < left) {
  16. robot(left, right + 1, n, tmp + ")", ans);
  17. }
  18. }
  19. }

43 Multiply Strings

https://leetcode.com/problems/multiply-strings/

题目描述

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

代码

  1. class Solution {
  2. public String multiply(String num1, String num2) {
  3. int m = num1.length(), n = num2.length();
  4. int[] pos = new int[m + n];
  5. for(int i = m - 1; i >= 0; i--) {
  6. for(int j = n - 1; j >= 0; j--) {
  7. int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
  8. int p1 = i + j, p2 = i + j + 1;
  9. int sum = mul + pos[p2];
  10. pos[p1] += sum / 10;
  11. pos[p2] = (sum) % 10;
  12. }
  13. }
  14. StringBuilder sb = new StringBuilder();
  15. for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p);
  16. return sb.length() == 0 ? "0" : sb.toString();
  17. }
  18. }

49 Group Anagrams

https://leetcode.com/problems/group-anagrams/

题目描述

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note: All inputs will be in lower-case.

代码

  1. class Solution {
  2. public List<List<String>> groupAnagrams(String[] strs) {
  3. Map<String, List<String>> map = new HashMap<>();
  4. for (String s : strs) {
  5. // sort by letter
  6. char[] array = s.toCharArray();
  7. Arrays.sort(array);
  8. String sortString = String.valueOf(array);
  9. if (map.containsKey(sortString)) {
  10. map.get(sortString).add(s);
  11. } else {
  12. List<String> list = new ArrayList<>();
  13. list.add(s);
  14. map.put(sortString, list);
  15. }
  16. }
  17. return new ArrayList<>(map.values());
  18. }
  19. }

76 Minimum Window Substring

https://leetcode.com/problems/minimum-window-substring/

题目描述

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

代码

  1. class Solution {
  2. public String minWindow(String s, String t) {
  3. if (s == null || s.length() < t.length() || s.length() == 0) {
  4. return "";
  5. }
  6. Map<Character, Integer> map = new HashMap<>();
  7. for (char c : t.toCharArray()) {
  8. if (map.containsKey(c)) {
  9. map.put(c, map.get(c) + 1);
  10. } else {
  11. map.put(c, 1);
  12. }
  13. }
  14. int left = 0;
  15. int minLeft = 0;
  16. int minLen = Integer.MAX_VALUE;
  17. int count = 0;
  18. for (int right = 0; right < s.length(); right++) {
  19. char c = s.charAt(right);
  20. if (map.containsKey(c)) {
  21. map.put(c, map.get(c) - 1);
  22. if (map.get(c) >= 0) {
  23. count++;
  24. }
  25. while (count == t.length()) {
  26. if (right - left + 1 < minLen) {
  27. minLeft = left;
  28. minLen = right - left + 1;
  29. }
  30. if (map.containsKey(s.charAt(left))) {
  31. map.put(s.charAt(left), map.get(s.charAt(left)) + 1);
  32. if (map.get(s.charAt(left)) > 0) {
  33. count--;
  34. }
  35. }
  36. left++;
  37. }
  38. }
  39. }
  40. if (minLen > s.length()) {
  41. return "";
  42. }
  43. return s.substring(minLeft, minLeft + minLen);
  44. }
  45. }

93 Restore IP Addresses

https://leetcode.com/problems/restore-ip-addresses/

题目描述

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

代码

  1. class Solution {
  2. public List<String> restoreIpAddresses(String s) {
  3. List<String> ans = new ArrayList<>();
  4. if (s == null || s.length() == 0) {
  5. return ans;
  6. }
  7. robot(0, 0, "", ans, s);
  8. return ans;
  9. }
  10. private void robot(int pos, int dot, String tmp, List<String> ans, String s) {
  11. if (pos >= s.length()) {
  12. return;
  13. }
  14. if (dot == 3) {
  15. // 防止都是0的情况,出现0.0.0.0000
  16. if (isValid(s.substring(pos)) && s.length() - pos <= 3) {
  17. ans.add(tmp + s.substring(pos));
  18. return;
  19. } else {
  20. return;
  21. }
  22. }
  23. for (int i = 1; i <= 3; i++) {
  24. if (pos + i <= s.length() && isValid(s.substring(pos, pos + i))) {
  25. robot(pos + i, dot + 1, tmp + s.substring(pos, pos + i) + ".", ans, s);
  26. }
  27. }
  28. }
  29. private boolean isValid(String string) {
  30. if (string.length() > 3) {
  31. return false;
  32. }
  33. int v = Integer.valueOf(string);
  34. if (string.charAt(0) == '0' && string.length() > 1) {
  35. return false;
  36. }
  37. return v >= 0 && v <= 255;
  38. }
  39. }

165 Compare Version Numbers

https://leetcode.com/problems/compare-version-numbers/

题目描述

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37

Credits:Special thanks to @ts for adding this problem and creating all test cases.

代码

  1. class Solution {
  2. public int compareVersion(String version1, String version2) {
  3. String[] v1 = version1.split("\\.");
  4. String[] v2 = version2.split("\\.");
  5. int m = Math.max(v1.length, v2.length);
  6. v1 = Arrays.copyOf(v1, m);
  7. v2 = Arrays.copyOf(v2, m);
  8. for (int i = 0; i < m; i++) {
  9. int n1 = 0;
  10. int n2 = 0;
  11. if (v1[i] != null) {
  12. n1 = Integer.valueOf(v1[i]);
  13. }
  14. if (v2[i] != null) {
  15. n2 = Integer.valueOf(v2[i]);
  16. }
  17. if (n1 < n2) {
  18. return -1;
  19. } else if (n1 > n2) {
  20. return 1;
  21. }
  22. }
  23. return 0;
  24. }
  25. }

227 Basic Calculator II

https://leetcode.com/problems/basic-calculator-ii/

题目描述

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

Credits:Special thanks to @ts for adding this problem and creating all test cases.

代码

  1. class Solution {
  2. public int calculate(String s) {
  3. int ans = 0;
  4. if (s == null || s.length() == 0) {
  5. return ans;
  6. }
  7. Deque<Integer> deque = new LinkedList<>();
  8. char operator = '+'; // 记录上一个操作符
  9. int tmp = 0;
  10. for (int i = 0; i < s.length() || tmp > 0; i++) {
  11. char c = i < s.length() ? s.charAt(i) : '+';
  12. if (c == ' ') {
  13. continue;
  14. }
  15. if (c >= '0' && c <= '9') {
  16. tmp = tmp * 10 + c - '0';
  17. } else {
  18. switch (operator) {
  19. case '+':
  20. deque.add(tmp);
  21. break;
  22. case '-':
  23. deque.add(-tmp);
  24. break;
  25. case '*':
  26. deque.add(deque.pollLast() * tmp);
  27. break;
  28. case '/':
  29. deque.add(deque.pollLast() / tmp);
  30. break;
  31. }
  32. tmp = 0;
  33. operator = c;
  34. }
  35. }
  36. for (int v : deque) {
  37. ans += v;
  38. }
  39. return ans;
  40. }
  41. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注