原题:力扣93.
class RestoreIpAddresses {
List<String> result = new ArrayList<>();
public List<String> restoreIpAddress(String s) {
// ip中的数字最少四个,最多十二个
if (s.length() < 4 || s.length() > 12) {
return result;
}
backTrack(s, 0, 0);
return result;
}
// 字符串,起始位置,添加小数点的数量
private void backTrack (String s, int startIndex, int pointNum) {
// 小数点为 3 个的时候分割就要结束了,就要判断最后一段是否合法
if (pointNum == 3) {
// 判断最后一段字符串是否合法
if (isValid(s, startIndex, s.length() - 1)) {
result.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isValid(s, startIndex, i)) {
s = s.substring(0, i + 1) + "." + s.substring(i + 1);
pointNum++;
backTrack(s, i + 2, pointNum);
pointNum--;
s = s.substring(0, i + 1) + s.substring(i + 2);
} else {
break;
}
}
}
private boolean isValid(String s, int start, int end) {
if (start > end) {
return false;
}
// 0 开头不合法,但是当只有一位数的时候可以是 0
if (s.charAt(start) == '0' && start != end) {
return false;
}
int num = 0;
for (int i = start; i <= end; i++) {
if (s.charAt(i) > '9' || s.charAt(i) < '0') {
return false;
}
num = num * 10 + (s.charAt(i) - '0');
if (num > 255) {
return false;
}
}
return true;
}
}
原题:力扣17.
用数组存储按键和字母的映射,数组的下标为 0 和 1 的位置不存储字母,和题目对应。
class LetterCombinations {
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return list;
}
String[] numString = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
backTracking(digits, numString, 0);
return list;
}
// 涉及大量字符串拼接,使用 StringBuilder ,是全局变量
StringBuilder temp = new StringBuilder();
public void backTracking(String digits, String[] numString, int num) {
if (num == digits.length()) {
list.add(temp.toString());
return;
}
String str = numString[digits.charAt(num) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
backTracking(digits, numString, num + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}
原题:力扣22.
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<String>();
backtrack(ans, new StringBuilder(), 0, 0, n);
return ans;
}
public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max) {
if (cur.length() == max * 2) {
ans.add(cur.toString());
return;
}
if (open < max) {
cur.append('(');
backtrack(ans, cur, open + 1, close, max);
cur.deleteCharAt(cur.length() - 1);
}
if (close < open) {
cur.append(')');
backtrack(ans, cur, open, close + 1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
}
如果对您有帮助,请点赞关注支持我,谢谢! ❤
如有错误或者不足之处,敬请指正! ❤
个人主页:星不易 ❤
算法通关村专栏:不易|算法通关村 ❤