算法学习

3、

package main

import (
	"fmt"
)

func max(x int, y int) int {
	if x < y {
		return y
	}
	return x
}
// 窗口滑动 解决子串问题
// 获取最长非重复子串   示例: "acdfeabac" > "acdfe"
func getLongestNotRepeat(s string) int {
	l := 0
	r := 0
	slen := len(s)

	currentLen := 1
	currentShou := s[l]
	for ;r<slen;r++ {
		if l >= r  {
			continue
		}else if currentShou == s[r] {
			fmt.Println(s[l:r])
			currentLen = max(currentLen, r-l)
			l++
		}
	}
	return currentLen
}


func climbStairs(n int) int {
	result := 0
	if n <= 0 {
		return 0
	}
	for _,step := range []int{1,2} {
		if n-step == 0 {
			result++
		} else if n-step >0 {
			result = result + climbStairs(n-step)
		} else if n-step <0 {
			continue
		}
	}
	return result
}

type ListNode struct {
	data int
	Next *ListNode
}




func main() {
	a := getLongestNotRepeat("acdfeabac")
	fmt.Println(a)

	fmt.Println(climbStairs(10))
}

  

 

2、读取大文件(5G/10G/1T)

for line in fp.readlines():  #如果line很长时,不合适

for a in fp.read(block_size): # 按块读取

 

 

1. threading.Semaphore(value=1) 线程信号量,可以用来控制线程线程的阻塞和释放

sm.acquire()  获取一个信号量,信号量-1,不够-1,则线程阻塞

sm.release()  释放一个信号量,信号量+1

示例如下,控制三个线程的执行顺序:

# -*- coding: utf-8 -*-
import threading
import time

sm0 = threading.Semaphore()
sm1 = threading.Semaphore(0)
sm2 = threading.Semaphore(0)

a = 0


def print1():
    global a
    while True:
        sm1.acquire()
        if a % 2 == 1:
            print(a, "----", a, threading.currentThread().name)
            a = a + 1
            time.sleep(1)
        sm0.release()


def print2():
    global a
    while True:
        sm2.acquire()
        if a % 2 == 0:
            print(a, "----", a, threading.currentThread().name)
            a = a + 1
            time.sleep(1)
        sm0.release()


def print0():
    global a
    while True:
        sm0.acquire()
        print(0, "----", a)
        time.sleep(1)
        if a % 2 == 1:
            sm1.release()
        else:
            sm2.release()


if __name__ == '__main__':
    t1 = threading.Thread(target=print1)
    t0 = threading.Thread(target=print0)
    t2 = threading.Thread(target=print2)
    t0.start()
    t1.start()
    t2.start()

  

 

posted @ 2020-05-23 11:06  zipon  阅读(185)  评论(0编辑  收藏  举报