[关闭]
@Yano 2015-12-30T03:24:28.000000Z 字数 10359 阅读 8431

LeetCode之String题目汇总

LeetCode

我的博客:http://blog.csdn.net/yano_nankai
LeetCode题解:https://github.com/LjyYano/LeetCode


LeetCode 题目汇总

LeetCode之Array题目汇总
LeetCode之Hash Table题目汇总
LeetCode之Linked List题目汇总
LeetCode之Math题目汇总
LeetCode之String题目汇总
LeetCode之Binary Search题目汇总
LeetCode之Divide and Conquer题目汇总
LeetCode之Dynamic Programming题目汇总
LeetCode之Backtracing题目汇总
LeetCode之Stack题目汇总
LeetCode之Sort题目汇总
LeetCode之Bit Manipulation题目汇总
LeetCode之Tree题目汇总
LeetCode之Depth-first Search题目汇总
LeetCode之Breadth-first Search题目汇总
LeetCode之Graph题目汇总
LeetCode之Trie题目汇总
LeetCode之Design题目汇总


文章目录:


Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.


  1. public String countAndSay(int n) {
  2. String init = "1";
  3. for (int i = 1; i < n; i++) {
  4. init = countAndSay(init);
  5. }
  6. return init;
  7. }
  8. String countAndSay(String string) {
  9. char[] str = string.toCharArray();
  10. String s = "";
  11. int p = 1;
  12. int count = 1;
  13. char last = str[0];
  14. for (; p < str.length; p++) {
  15. if (str[p] == last) {
  16. count++;
  17. } else {
  18. s += "" + count + last;
  19. count = 1;
  20. last = str[p];
  21. }
  22. }
  23. s += "" + count + last;
  24. return s;
  25. }

Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.


斐波那契数列和台阶问题的变形,只不过加了一个条件判断。

  1. public int numDecodings(String s) {
  2. if (s == null || s.length() == 0) {
  3. return 0;
  4. }
  5. int n = s.length();
  6. char[] c = s.toCharArray();
  7. // 对于台阶,需要前两步的值,所以数组最小是3
  8. int[] step = new int[Math.max(n + 1, 3)];
  9. step[0] = 1;
  10. step[1] = 0;
  11. // 第一个字符不是0,则第一步初始为1
  12. if (c[0] != '0') {
  13. step[1] = 1;
  14. }
  15. // step[i] = step[i - 1] + step[i - 2];
  16. // 只不过加step[i - 2]时,需要对c[i - 2]和c[i - 1]判断,组合是否<=26
  17. for (int i = 2; i <= n; i++) {
  18. step[i] = 0;
  19. if (c[i - 1] != '0') {
  20. step[i] += step[i - 1];
  21. }
  22. if (c[i - 2] != '0') {
  23. if ((c[i - 2] - '0') * 10 + (c[i - 1] - '0') <= 26) {
  24. step[i] += step[i - 2];
  25. }
  26. }
  27. }
  28. return step[n];
  29. }

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. public List<String> generateParenthesis(int n) {
  2. if (n <= 0) {
  3. return new ArrayList<String>();
  4. }
  5. ArrayList<String> rt = new ArrayList<String>();
  6. dfs(rt, "", n, n);
  7. return rt;
  8. }
  9. void dfs(ArrayList<String> rt, String s, int left, int right) {
  10. if (left > right) {
  11. return;
  12. }
  13. if (left == 0 && right == 0) {
  14. rt.add(s);
  15. }
  16. if (left > 0) {
  17. dfs(rt, s + "(", left - 1, right);
  18. }
  19. if (right > 0) {
  20. dfs(rt, s + ")", left, right - 1);
  21. }
  22. }

Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.


  1. public int strStr(String haystack, String needle) {
  2. if (haystack == null || needle == null
  3. || haystack.length() < needle.length()) {
  4. return -1;
  5. }
  6. if (needle.length() == 0) {
  7. return 0;
  8. }
  9. for (int i = 0; i < haystack.length(); i++) {
  10. if (i + needle.length() > haystack.length()) {
  11. return -1;
  12. }
  13. int m = i;
  14. for (int j = 0; j < needle.length(); j++) {
  15. if (needle.charAt(j) == haystack.charAt(m)) {
  16. if (j == needle.length() - 1) {
  17. return i;
  18. }
  19. m++;
  20. } else {
  21. break;
  22. }
  23. }
  24. }
  25. return -1;
  26. }

Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example, 
Given s = "Hello World",
return 5.


  1. public int lengthOfLastWord(String s) {
  2. if (s == null || s.length() == 0) {
  3. return 0;
  4. }
  5. int len = 0;
  6. int i = s.length() - 1;
  7. while (i >= 0 && s.charAt(i) == ' ') {
  8. i--;
  9. }
  10. while (i >= 0 && s.charAt(i) != ' ') {
  11. len++;
  12. i--;
  13. }
  14. return len;
  15. }

 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. static final char[][] CHAR_MAP = { {},// 0
  2. {},// 1
  3. { 'a', 'b', 'c' },// 2
  4. { 'd', 'e', 'f' },// 3
  5. { 'g', 'h', 'i' },// 4
  6. { 'j', 'k', 'l' },// 5
  7. { 'm', 'n', 'o' },// 6
  8. { 'p', 'q', 'r', 's' },// 7
  9. { 't', 'u', 'v' },// 8
  10. { 'w', 'x', 'y', 'z' } // 9
  11. };
  12. List<String> result;
  13. char[] stack;
  14. public List<String> letterCombinations(String digits) {
  15. if (digits == null || digits.length() == 0) {
  16. return new ArrayList<String>();
  17. }
  18. result = new ArrayList<String>();
  19. stack = new char[digits.length()];
  20. dfs(digits.toCharArray(), 0);
  21. return result;
  22. }
  23. private void dfs(char[] digits, int p) {
  24. if (p == digits.length) {
  25. result.add(new String(stack));
  26. } else {
  27. int num = digits[p] - '0';
  28. for (char c : CHAR_MAP[num]) {
  29. stack[p] = c;
  30. dfs(digits, p + 1);
  31. }
  32. }
  33. }

Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.


  1. public String longestCommonPrefix(String[] strs) {
  2. if (strs == null || strs.length == 0) {
  3. return "";
  4. }
  5. if (strs.length == 1) {
  6. return strs[0];
  7. }
  8. String string = strs[0];
  9. for (int i = 0; i < string.length(); i++) {
  10. for (int j = 1; j < strs.length; j++) {
  11. if (!(i < strs[j].length() && string.charAt(i) == strs[j]
  12. .charAt(i))) {
  13. return string.substring(0, i);
  14. }
  15. }
  16. }
  17. return string;
  18. }

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, and there exists one unique longest palindromic substring.


  1. public String longestPalindrome(String s) {
  2. if (s == null || s.length() == 0) {
  3. return "";
  4. }
  5. int start = 0;
  6. int end = 0;
  7. for (int i = 0; i < s.length() - 1; i++) {
  8. int len1 = longest(s, i, i);
  9. int len2 = longest(s, i, i + 1);
  10. int len = Math.max(len1, len2);
  11. if (end - start < len) {
  12. start = i - (len - 1) / 2;
  13. end = i + len / 2;
  14. }
  15. }
  16. return s.substring(start, end + 1);
  17. }
  18. private int longest(String s, int left, int right) {
  19. while (left >= 0 && right < s.length()
  20. && s.charAt(left) == s.charAt(right)) {
  21. left--;
  22. right++;
  23. }
  24. return right - left - 1;
  25. }

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


  1. public int lengthOfLongestSubstring(String s) {
  2. if (s == null) {
  3. return 0;
  4. }
  5. if (s.length() == 0 || s.length() == 1) {
  6. return s.length();
  7. }
  8. char[] c = s.toCharArray();
  9. // barrier:0~i中,第一个不重复字符的位置
  10. int barrier = 0;
  11. int maxLen = 1;
  12. for (int i = 1; i < c.length; i++) {
  13. for (int j = i - 1; j >= barrier; j--) {
  14. if (c[i] == c[j]) {
  15. // 第一个不重复字符的位置为j+1,因为每次j从i-1递减到barrier
  16. barrier = j + 1;
  17. break;
  18. }
  19. }
  20. maxLen = Math.max(maxLen, i - barrier + 1);
  21. }
  22. return maxLen;
  23. }

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. List<String> rt = new ArrayList<String>();
  2. String[] stack = new String[4];
  3. public List<String> restoreIpAddresses(String s) {
  4. if (s == null || s.length() == 0) {
  5. return new ArrayList<String>();
  6. }
  7. dfs(s, 0, 0);
  8. return rt;
  9. }
  10. /**
  11. *
  12. * @param s
  13. * @param p
  14. * :指针
  15. * @param pstack
  16. * :stack的下标
  17. */
  18. public void dfs(String s, int p, int pstack) {
  19. if (pstack == 4) {
  20. // 如果stack长度为4,且s的字符全部用上
  21. // 则stack[0...3]存了一个结果
  22. if (p >= s.length()) {
  23. String ip = String.join(".", stack);
  24. rt.add(ip);
  25. }
  26. return;
  27. }
  28. // 获取1~3个字符
  29. for (int i = 1; i <= 3; i++) {
  30. // 如果超过字符串长度,返回
  31. if (p + i > s.length()) {
  32. return;
  33. }
  34. // 若选取的第一个字符是0,则停止选取
  35. if (i > 1 && s.charAt(p) == '0') {
  36. continue;
  37. }
  38. String number = s.substring(p, p + i);
  39. // 如果number<=255,递归
  40. if (Integer.parseInt(number) <= 255) {
  41. stack[pstack] = number;
  42. dfs(s, p + i, pstack + 1);
  43. }
  44. }
  45. }

Reverse Words in a String

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:


常规的做法是:

  1. 将字符串首尾的空格(leading or trailing spaces)去掉
  2. 翻转每个单词
  3. 翻转整个字符串

例如字符串:“the sky”

翻转前:

  1. the sky

翻转每个单词:

  1. eht yks

翻转整个字符串:

  1. sky the

利用Java的API,解这个题目只需要3行代码。 
参考自:Reverse Words in a String

  1. public String reverseWords(String s) {
  2. List<String> words = Arrays.asList(s.trim().split(" +"));
  3. Collections.reverse(words);
  4. return String.join(" ", words);
  5. }

Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

Corner Cases:


  1. public String simplifyPath(String path) {
  2. if (path == null) {
  3. return null;
  4. }
  5. String[] names = path.split("/");
  6. int eat = 0;
  7. LinkedList<String> stack = new LinkedList<String>();
  8. for (int i = names.length - 1; i >= 0; i--) {
  9. String token = names[i];
  10. // token是"..", 表示上级路径,前一个路径不打印
  11. // token是".", 表示当前路径,自身不打印
  12. // token是"", 表示为两个"/"相连,不做操作
  13. // eat>0,表示左边不打印
  14. // 否则,将token入栈
  15. if (token.equals("..")) {
  16. eat++;
  17. } else if (token.equals(".")) {
  18. // do nothing
  19. } else if (token.equals("")) {
  20. // do nothing
  21. } else {
  22. if (eat > 0) {
  23. eat--;
  24. } else {
  25. stack.push(token);
  26. }
  27. }
  28. }
  29. StringBuilder s = new StringBuilder();
  30. s.append("/");
  31. // 最后一个不加"/",所以while判断条件是>1
  32. while (stack.size() > 1) {
  33. s.append(stack.pop());
  34. s.append("/");
  35. }
  36. // 最后一个不加"/"
  37. if (!stack.isEmpty()) {
  38. s.append(stack.pop());
  39. }
  40. return s.toString();
  41. }

Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.


  1. public boolean isPalindrome(String s) {
  2. if (s.length() <= 1) {
  3. return true;
  4. }
  5. char[] chars = s.toLowerCase().toCharArray();
  6. for (int st = 0, ed = chars.length - 1; st <= ed; st++, ed--) {
  7. while (st < ed && !isValid(s, st))
  8. st++;
  9. while (st < ed && !isValid(s, ed))
  10. ed--;
  11. if (chars[st] != chars[ed])
  12. return false;
  13. }
  14. return true;
  15. }
  16. boolean isValid(String s, int i) {
  17. char c = s.charAt(i);
  18. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')
  19. || (c >= 'A' && c <= 'Z');
  20. }

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. public boolean isValid(String s) {
  2. if (s == null || s.length() % 2 == 1) {
  3. return false;
  4. }
  5. HashMap<Character, Character> map = new HashMap<Character, Character>();
  6. map.put('(', ')');
  7. map.put('[', ']');
  8. map.put('{', '}');
  9. Stack<Character> stack = new Stack<Character>();
  10. for (int i = 0; i < s.length(); i++) {
  11. char c = s.charAt(i);
  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. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注