class Solution {
public int subarraySum(int[] nums, int k) {
int left=0;
int sum=0;
int count =0;
for(int right = 0;right<nums.length;right++){
sum+=nums[right];
while(sum > k && left<=right){
left++;
sum-=nums[left-1];
}
if(sum == k){
count++;
}
}
return count;
}
}
/**
* 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 ListNode mergeKLists(ListNode[] lists) {
//链表里面的数都拿出来,排序后再插入链表;
List<Integer> numlist = new ArrayList<>();
for(int i =0;i<lists.length;i++){
ListNode head = lists[i];
while(head != null){
numlist.add(head.val);
head = head.next;
}
}
Collections.sort(numlist);
ListNode dummy = new ListNode();
ListNode cur = dummy;
for(int val:numlist){
cur.next = new ListNode(val);
cur = cur.next;
}
return dummy.next;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int sum;
public TreeNode convertBST(TreeNode root) {
//递归
if(root != null){
convertBST(root.right);
sum+=root.val;
root.val=sum;
convertBST(root.left);
}
return root;
}
}
class Solution {
public int longestValidParentheses(String s) {
//栈
int res =0;
Stack<Integer> st = new Stack<>();
st.push(-1);
for(int i = 0;i<s.length();i++){
if(s.charAt(i)=='('){
st.push(i);
}else{
st.pop();
if(st.isEmpty()){
st.push(i);
}else{
res = Math.max(res,i-st.peek());
}
}
}
return res;
}
}
class Solution {
public List<String> removeInvalidParentheses(String s) {
//递归,试一下删除一个行不行
//visited防止重复 set
Set<String> visited = new HashSet<>();
Queue<String> que = new LinkedList<>();
List<String> res = new ArrayList<>();
if(s==null){
return res;
}
boolean success = false;
que.add(s);
visited.add(s);
while(!que.isEmpty()){
String cur = que.poll();
if(ifCorrect(cur)){
res.add(cur);
success = true;
}
if(success){
continue;
}
//如果不成立一次删除一个
for(int i = 0;i<cur.length();i++){
if(cur.charAt(i)!='(' && cur.charAt(i)!=')'){
continue;
}
String next = cur.substring(0,i) + cur.substring(i+1);
if(!visited.contains(next)){
visited.add(next);
que.add(next);
}
}
}
return res;
}
private boolean ifCorrect(String s){
int count=0;
for(char ch:s.toCharArray()){
if(ch !='(' && ch !=')' ){
continue;
}
if(ch =='('){
count +=1;
}else{
count -=1;
if(count<0){
return false;
}
}
}
return count==0;
}
}