leetcode解题

This commit is contained in:
wu xiangkai
2025-10-22 16:35:11 +08:00
parent 75c4bd8473
commit 7bbd47f65f
3 changed files with 107 additions and 0 deletions

40
125.valid-palindrome.java Normal file
View File

@@ -0,0 +1,40 @@
/*
* @lc app=leetcode id=125 lang=java
*
* [125] Valid Palindrome
*/
// @lc code=start
class Solution {
public boolean isPalindrome(String s) {
int i = 0, j = s.length()-1;
boolean r = true;
while(i < j) {
while(i<j && !isAlphanumberic(s.charAt(i))) {
i++;
}
while(i<j && !isAlphanumberic(s.charAt(j))) {
j--;
}
if(i==j) {
break;
}
if(!isSameLeterIgnoreCase(s.charAt(i), s.charAt(j))) {
r = false;
break;
}
}
return r;
}
private boolean isAlphanumberic(char c) {
return c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z' || c >='0' && c <= '9';
}
private boolean isSameLeterIgnoreCase(char a, char b) {
return a == b || a - b == 'z' - 'a' || a - b == 'a' - 'z';
}
}
// @lc code=end

26
136.single-number.java Normal file
View File

@@ -0,0 +1,26 @@
/*
* @lc app=leetcode id=136 lang=java
*
* [136] Single Number
*/
// @lc code=start
class Solution {
/**
* 可以通过对数组中所有整数进行异或来找出该数,
* 因为对于出现两次的整数异或之后都为0
* 而对于只出现过一次的整数和0异或之后为其本身
*
* @param nums
* @return
*/
public int singleNumber(int[] nums) {
int r = 0;
for(int i = 0; i < nums.length; i++) {
r = r ^ nums[i];
}
return r;
}
}
// @lc code=end

View File

@@ -0,0 +1,41 @@
/*
* @lc app=leetcode id=141 lang=java
*
* [141] Linked List Cycle
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* 快慢指针,若链表中存在环,则快指针一次动两步,慢指针一次动一步,快指针一定会赶上慢指针
*
* @param head
* @return
*/
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
boolean isCycle = false;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if(fast == slow) {
isCycle = true;
break;
}
}
return isCycle;
}
}
// @lc code=end