不得不说,周末要去考软考了,有点小慌张。天气冷了,早上起床好难受啊!!
主要内容
单例模式的实现方式
滑动窗口算法解leetcode[3]Longest Substring Without Repeating Characters
单例模式的实现方式 我能想到的单例模式的实现方式一共有5中:
懒汉式
饿汉式
双重锁判断机制实现单例
静态内部类实现
枚举类实现
懒汉式单例模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class Singleton { private static Singleton instance; private Singleton () {} public static synchronized Singleton getSingleton () { if (instance==null ){ instance=new Singleton (); } return instance; } }
优点:
可以实现延时加载
线程安全 缺点:
效率不高
饿汉式单例模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Singleton { private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getSingleton () { return instance; } }
优点:
线程安全
调用效率搞 缺点:
不能实现延时加载
双重锁判断机制实现单例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public class Singleton { private static Singleton instance; private Singleton () {} public static Singleton getSingleton () { if (instance==null ){ synchronized (Singleton.class){ if (instance==null ){ instance=new Singleton (); } } } return instance; } }
优点:
延迟加载
调用效率较高 缺点:
因为JVM底层的原因,偶尔会出问题
静态内部类实现单例模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Singleton { private static class SingletonClassInstance { private static final Singleton INSTANCE = new Singleton (); } private Singleton () {} public static Singleton getInstance () { return SingletonClassInstance.INSTANCE; } }
优点:
线程安全
调用效率高
可以实现延迟加载
使用枚举类实现单例模式 1 2 3 4 5 6 7 8 9 10 11 12 13 public enum Singleton { INSTANCE; public void operation () { } }
优点:
线程安全
调用效率高
能够天然的放置反射和反序列化调用
缺点:
不能实现延迟加载
滑动窗口算法解leetcode[3]Longest Substring Without Repeating Characters 题目描述 Given a string, find the length of the longest substring without repeating characters.
Example 1: Input: “abcabcbb” Output: 3 Explanation: The answer is “abc”, with the length of 3.
Example 2: Input: “bbbbb” Output: 1 Explanation: The answer is “b”, with the length of 1.
Example 3: Input: “pwwkew” Output: 3 Explanation: The answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
解题思路 使用两个指针l,r来标识区间[l,r]为滑动窗口。 并且使用一个数组来记录窗口内字符出现的次数,整个数组充当了map的角色 最初窗口大小是0的,右指针向右扩展,直到右边的字符已经在窗口中出现了,这个时候我们让左指针向右拓展(窗口在缩小)直到窗口内没有重复的字符串。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public int lengthOfLongestSubstring (String s) { char [] chars = s.toCharArray(); int [] freq = new int [256 ]; int l = 0 ; int r = -1 ; int res = 0 ; while (l<chars.length){ if ((r<s.length()-1 )&&freq[chars[r+1 ]]==0 ){ ++r; freq[chars[r]]++; }else { freq[chars[l]]--; l++; } res=Math.max(res,r-l+1 ); } return res; } }