今日题目
1、链表每k组反转
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if(head==null||head.next==null||k<2){
return head;
}
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode curr=head,pre=dummy,temp;
int len=0;
while(head!=null){
len++;
head=head.next;
}
for(int i=0;i<len/k;i++){
for(int j=1;j<k;j++){
//头插法,画下图就理解了
temp=curr.next;
curr.next=temp.next;
temp.next=pre.next;
pre.next=temp;
}
pre=curr;
curr=curr.next;
}
return dummy.next;
}
}
2、 删除链表的倒数第n个节点
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if(head==null||head.next==null||k<2){
return head;
}
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode curr=head,pre=dummy,temp;
int len=0;
while(head!=null){
len++;
head=head.next;
}
for(int i=0;i<len/k;i++){
for(int j=1;j<k;j++){
//头插法,画下图就理解了
temp=curr.next;
curr.next=temp.next;
temp.next=pre.next;
pre.next=temp;
}
pre=curr;
curr=curr.next;
}
return dummy.next;
}
}
3、 两个栈来实现一个队列
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
4、 有效的括号
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return bool布尔型
*/
public boolean isValid (String s) {
// write code here
Stack<Character> stack =new Stack<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='['){
stack.push(']');
}else if(s.charAt(i)=='('){
stack.push(')');
}else if(s.charAt(i)=='{'){
stack.push('}');
}else if(stack.isEmpty()||s.charAt(i)!=stack.pop()){//要先判断栈内是否为空
return false;
}
}
return stack.size()==0;//最后栈清空才能是true
}
}
5、最长公共字串
import java.util.*;
public class Solution {
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
public String LCS (String str1, String str2) {
// write code here
int m=str1.length(),n=str2.length();
int[][] dp=new int[m+1][n+1];
int max=0,index=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(str1.charAt(i)==str2.charAt(j)){
dp[i+1][j+1]=dp[i][j]+1;
if(max<dp[i+1][j+1]){
max=dp[i+1][j+1];
index=i+1;
}
}
}
}
return str1.substring(index-max,index);
}
}