125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
检查是否为回文
方法一
class Solution {
public boolean isPalindrome(String s) {
int i = 0;
int length = s.length();
int j = length - 1;
char[] chars = s.toLowerCase().toCharArray();
while (i<j) {
char chI = chars[i];
char chJ = chars[j];
if ( !Character.isLetterOrDigit(chI) ) {
++i;
continue;
}
if ( !Character.isLetterOrDigit(chJ) ) {
--j;
continue;
}
if (chI != chJ) {
return false;
}
++i;
--j;
}
return true;
}
}
方法2
class Solution {
public static final char[] charmap = new char[255];
static {
for(int i=0;i<10;i++)
{
charmap[i+'0']=(char)(i+1);// '0'+1 错
}
for(int i=0;i<26;i++)
{
charmap[i+'a']= charmap[i+'A']=(char)(i+11);
}
}
public boolean isPalindrome(String s) {
if(s.equals("")) return true;
if(s.isEmpty()) return false;
int st=0;
int ed=s.length()-1;
char stchr;
char edchr;
while(st<ed)
{
stchr =charmap[s.charAt(st)];
edchr =charmap[s.charAt(ed)];
if(stchr!=0&&edchr!=0)
{
if(stchr!=edchr) return false;
st++;
ed--;
}
else
{
if(stchr==0) st++;
if(edchr==0) ed--;
}
}
return true;
}
}
136. Single Number
求出数组中唯一的那个数字
class Solution {
public int singleNumber(int[] nums) {
int res=0;
for(int num:nums)
{
res^=num;
}
return res;
}
}
141. Linked List Cycle
检查链表有没有环
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast=head;
ListNode low=head;
while(fast!=null)
{
if(fast.next!=null)
{
fast=fast.next.next;
}
else
{
return false;
}
low=low.next;
if(low==fast) return true;
}
return false;
}
}
155. Min Stack
最小栈
方法一
class MinStack {
Stack<Integer> stack;
Stack<Integer> min;
/** initialize your data structure here. */
public MinStack() {
stack=new Stack();
min = new Stack();
}
public void push(int x) {
stack.push(x);
if(min.isEmpty()||min.peek()>=x)//等于号 不能漏要想清楚
{
min.push(x);
}
}
public void pop() {
int pop;
if(!stack.isEmpty())
{
pop=stack.pop();
if(min.peek()==pop) min.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
if(!min.isEmpty())
{
return min.peek();
}
else
{
return 0;
}
}
}
方法2
class MinStack {
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head==null)
{
head = new Node(x,x,null);
}
else
{
head=new Node(x,Math.min(head.min,x),head);
}
}
public void pop() {
head=head.next;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
static class Node{
int val ;
int min ;
Node next;
public Node(int val,int min,Node next)
{
this.val=val;
this.min=min;
this.next=next;
}
}
}