50,781
社区成员
发帖
与我相关
我的任务
分享
第一题
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head, fast = head, pre = head;
while (fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
ListNode next = slow.next;
slow.next = null;
while (next != null) {
pre = slow;
slow = next;
next = next.next;
slow.next = pre;
}
ListNode newHead = slow;
while (head != null && newHead != null) {
if (head.val != newHead.val) {
return false;
}
newHead = newHead.next;
head = head.next;
}
return true;
}
}
第二题
class Solution {
public List<List<String>> partition(String s) {
int n = s.length();
boolean[][] dp = new boolean[n + 2][n + 2];
int[] tmp = new int[(n + 2) * (n + 2)];
int cnt = 0;
List<List<String>> ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (i == j) {
dp[i][j] = true;
} else {
if (s.charAt(i) == s.charAt(j)) {
if (i==j+1){
dp[i][j] = true;
}else {
dp[i][j] = dp[i - 1][j + 1];
}
} else {
dp[i][j] = false;
}
}
if (dp[i][j]) {
tmp[cnt] = i * 100 + j;
cnt++;
}
}
}
List<Set<String>> x = new ArrayList<>();
x.add(new HashSet<>());
x.get(0).add(s.charAt(0) + "#" + 0);
for (int i = 1; i < cnt; i++) {
int l = tmp[i] % 100;
int r = tmp[i] / 100;
Set<String> iSet = new HashSet<>();
x.add(iSet);
String tmpS = s.substring(l, r + 1);
for (int j = 0; j < i; j++) {
Set<String> y = x.get(j);
if (l == 0) {
iSet.add(tmpS + "#" + r);
}else {
for (String z : y) {
int hasr = Integer.parseInt(z.split("#")[1]);
if (l == hasr + 1) {
iSet.add(z.replace("#" + hasr, "") + "," + tmpS + "#" + r);
}
}
}
}
}
for (int i = 0; i < cnt; i++) {
Set<String> y = x.get(i);
for (String z : y) {
if (Integer.parseInt(z.split("#")[1]) == n - 1) {
String[] xx = z.replace("#" + (n - 1), "").split(",");
List<String> yy = new ArrayList<>();
for (int j = 0; j < xx.length; j++) {
yy.add(xx[j]);
}
ans.add(yy);
}
}
}
return ans;
}
}
第三题
class Solution {
public int primePalindrome(int n) {
while (true) {
if (n == reverse(n) && isPrime(n))
return n;
n++;
if (10_000_000 < n && n < 100_000_000)
n = 100_000_000;
}
}
public boolean isPrime(int n) {
if (n < 2) return false;
int R = (int) Math.sqrt(n);
for (int d = 2; d <= R; ++d)
if (n % d == 0) return false;
return true;
}
public int reverse(int n) {
int ans = 0;
while (n > 0) {
ans = 10 * ans + (n % 10);
n /= 10;
}
return ans;
}
}
第四题