Java Algorithm Tips and Tricks
Last updated
Last updated
在LeetCode上刷题自己常用的java类方法,总结了一下:
常用方法:
int
length()
返回字符串的长度
char
charAt(int)
返回某索引处的字符
boolean
isEmpty()
判断是否是空字符串
String
toLowerCase()
使用默认语言环境,将 String 中的所字符转换为小写
String
toUpperCase()
使用默认语言环境,将 String 中的所字符转换为大写
String
trim()
返回字符串的副本,忽略前导空白和尾部空白
boolean
equals(Object)
比较字符串的内容是否相同
boolean
equalsIgnoreCase(String)
与equals方法类似,忽略大小写
String
concat(String)
将指定字符串连接到此字符串的结尾。 等价于用“+”
int
compareTo(String)
比较两个字符串的大小
String
substring(int beginIndex)
返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。
String
substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。
boolean
endsWith(String suffix)
测试此字符串是否以指定的后缀结束
boolean
startsWith(String prefix)
测试此字符串是否以指定的前缀开始
boolean
startsWith(String prefix, int toffset)
测试此字符串从指定索引开始的子字符串是否以指定前缀开始
boolean
contains(CharSequence s)
当且仅当此字符串包含指定的 char 值序列时,返回 true
int
indexOf(String str)
返回指定子字符串在此字符串中第一次出现处的索引,未找到返回-1
int
indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始,未找到返回-1
int
lastIndexOf(String str)
返回指定子字符串在此字符串中最右边出现处的索引,未找到返回-1
int
lastIndexOf(String str, int fromIndex)
返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,未找到返回-1
替换
String
replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所 oldChar 得到的。
String
replace(CharSequence target, CharSequence replacement)
使用指定的字面值替换序列替换此字符串所匹配字面值目标序列的子字符串。
String
replaceAll(String regex, String replacement)
使用给定的replacement 替换此字符串所匹配给定的正则表达式的子字符串。
String
replaceFirst(String regex, String replacement)
使用给定的replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
匹配:
boolean
matches(String regex)
告知此字符串是否匹配给定的正则表达式。
切片:
String[]
split(String regex)
根据给定正则表达式的匹配拆分此字符串。
String[]
split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符>串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中。
1、构造方法
比较
基本功能
转化(String -> others)
转化(others->String)
替换
拆分
在Java中,不管是String.split(),还是正则表达式,有一些特殊字符需要转义, 这些字符是 ( [ { / ^ - $ ¦ } ] ) ? | * + . 转义方法为字符前面加上"\",这样在split、replaceAll时就不会报错了; 不过要注意,String.contains()方法不需要转义。
所以正常的写法是这样的: 1、如果用“.”作为分隔的话,必须是如下写法:String.split(“\.”),这样才能正确的分隔开,不能用String.split(“.”); 2、如果用“|”作为分隔的话,必须是如下写法:String.split(“\|”),这样才能正确的分隔开,不能用String.split(“|”); “.”和“|”都是转义字符,必须得加"\“; 3、如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如:“a=1 and b =2 or c=3”,把三个都分隔出来,可以用String.split(“and|or”); split分隔符总结 1.字符”|“,”*“,”+“都得加上转义字符,前面加上”\“。 2.而如果是” \ “,那么就得写成”\“。 3.如果一个字符串中有多个分隔符,可以用”|"作为连字符。
大小写
去掉首尾空白符
补充:字符串池
程序当中直接写上的双引号字符串,就在字符串常量池中
用+ 得到的
new出来的不在
当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。
和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。
StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)。
由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。
然而在应用程序要求线程安全的情况下,则必须使用 StringBuffer 类。
可变字符序列 StringBuilder是个字符串的缓冲区,即它是一个容器,容器中可以装很多字符串。并且能够对其中的字符串进 行各种操作。
构造方法:
常用方法:
例如:
用toString方法把StringBuilder转化成String //StringBuilder -> String
1.String –> 基本数据类型、包装类:调用包装类的静态方法 parseXxx(str)
int num = Integer.parseInt(str);
2.基本数据类型、包装类 –> String:调用String重载的 valueOf(xxx)
String str = str.valueOf(num);
1.String –> char[]:调用String的toCharArray()
char[] charArray = str.toCharArray();
2.char[] –> String:调用String的构造器
char[] arr = new char[]{‘h’,’e’,’l’,’l’,’o’};
String str = new String(arr);
1.String –> StringBuffer、StringBuilder:调用StringBuffer、StringBuilder构造器
StringBuffer sb = new StringBuffer(String str);
2.StringBuffer、StringBuilder –> String: ①调用String构造器;
String str = new String(StringBuffer sb);
②StringBuffer、StringBuilder的toString()
String str = sb.toString();
StringBuffer sb = new StringBuffer(String str);
1.增:append(xxx) 2.删:delete(int start,int end) 3.改:setCharAt(int n, char ch) / replace(int start, int end, String str)
4.查:charAt(int n ) 5.插:insert(int offset, xxx) 6.长度:length(); 7.遍历:for() + charAt() / toString()
List arrayList = new ArrayList<>(); Set set = new HashSet<>();
1.增:add(Object obj) 2.删:remove(int index) / remove(Object obj) 3.改:set(int index, Object ele) 4.查:get(int index) 5.插:add(int index, Object ele) 6.长度:size() 7.清空:clear(); 8.是否包含:contains(Object obj) 9.是否为空:isEmpty() 10.遍历:
① Iterator迭代器方式
② 增强for循环
③ 普通的循环
注意:
ArrayList对象不能存储基本类型,只能存储引用类型的数据。类似 < int > 不能写,但是存储基本数据类型对应的 包装类型是可以的。所以,想要存储基本类型数据, <> 中的数据类型,必须转换后才能编写
可以直接sout 变量名 回输出这种形式的[AAA,BBB,CCC] toString方法已经重写
不必重写equals方法和hashcode
1.添加:put(Object key,Object value) 2.删除:remove(Object key) 3.修改:put(Object key,Object value) 4.查询:get(Object key) 5.长度:size() 6.遍历:keySet() / values() / entrySet() 7.containsKey(Object key) 包含返回true,否则false 8.getOrDefault(Object key, int 0) 得到key对应的value,如果不存在返回自己设定的默认值
(2)通过keySet()和values()
boolean
add(E e)
将指定的元素插入此优先级队列。
void
clear()
从此优先级队列中移除所有元素。
Comparator<? super E>
comparator()
返回用来对此队列中的元素进行排序的比较器;如果此队列根据其元素的自然顺序进行排序,则返回 null。
boolean
contains(Object o)
如果此队列包含指定的元素,则返回 true。
Iterator
iterator()
返回在此队列中的元素上进行迭代的迭代器。
boolean
offer(E e)
将指定的元素插入此优先级队列。
E
peek()
获取但不移除此队列的头;如果此队列为空,则返回 null。
E
poll()
获取并移除此队列的头,如果此队列为空,则返回 null。
boolean
remove(Object o)
从此队列中移除指定元素的单个实例(如果存在)。
int
size()
返回此 collection 中的元素数。
Object[]
toArray()
返回一个包含此队列所有元素的数组。
boolean
isEmpty()
Returns true if this collection contains no elements
T[]
toArray(T[] a)
返回一个包含此队列所有元素的数组;返回数组的运行时类型是指定数组的类型。
从类 java.util.AbstractQueue 继承的方法: addAll, element, remove
从类 java.util.AbstractCollection 继承的方法: containsAll, isEmpty, removeAll, retainAll, toString
从类 java.lang.Object 继承的方法: clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
从接口 java.util.Collection 继承的方法: containsAll, equals, hashCode, isEmpty, removeAll, retainAll
boolean
The method checks the stack is empty or not.
E
The method pushes (insert) an element onto the top of the stack.
E
The method removes an element from the top of the stack and returns the same element as the value of that function.
E
The method looks at the top element of the stack without removing it.
int
The method searches the specified object and returns the position of the object.
Java Queue 是一个interface,不能直接实例化
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure.
Java LinkedList class can be used as a list, stack or queue
boolean add(object)
It is used to insert the specified element into this queue and return true upon success.
boolean offer(object)
It is used to insert the specified element into this queue.
Object remove()
It is used to retrieves and removes the head of this queue.
Object poll()
It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.
Object element()
It is used to retrieves, but does not remove, the head of this queue.
Object peek()
It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
boolean add(E e)
It is used to append the specified element to the end of a list.
void add(int index, E element)
It is used to insert the specified element at the specified position index in a list.
boolean addAll(Collection<? extends E> c)
It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
boolean addAll(Collection<? extends E> c)
It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
boolean addAll(int index, Collection<? extends E> c)
It is used to append all the elements in the specified collection, starting at the specified position of the list.
void addFirst(E e)
It is used to insert the given element at the beginning of a list.
void addLast(E e)
It is used to append the given element to the end of a list.
void clear()
It is used to remove all the elements from a list.
Object clone()
It is used to return a shallow copy of an ArrayList.
boolean contains(Object o)
It is used to return true if a list contains a specified element.
Iterator<E> descendingIterator()
It is used to return an iterator over the elements in a deque in reverse sequential order.
E element()
It is used to retrieve the first element of a list.
E get(int index)
It is used to return the element at the specified position in a list.
E getFirst()
It is used to return the first element in a list.
E getLast()
It is used to return the last element in a list.
int indexOf(Object o)
It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o)
It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element.
ListIterator<E> listIterator(int index)
It is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list.
boolean offer(E e)
It adds the specified element as the last element of a list.
boolean offerFirst(E e)
It inserts the specified element at the front of a list.
boolean offerLast(E e)
It inserts the specified element at the end of a list.
E peek()
It retrieves the first element of a list
E peekFirst()
It retrieves the first element of a list or returns null if a list is empty.
E peekLast()
It retrieves the last element of a list or returns null if a list is empty.
E poll()
It retrieves and removes the first element of a list.
E pollFirst()
It retrieves and removes the first element of a list, or returns null if a list is empty.
E pollLast()
It retrieves and removes the last element of a list, or returns null if a list is empty.
E pop()
It pops an element from the stack represented by a list.
void push(E e)
It pushes an element onto the stack represented by a list.
E remove()
It is used to retrieve and removes the first element of a list.
E remove(int index)
It is used to remove the element at the specified position in a list.
boolean remove(Object o)
It is used to remove the first occurrence of the specified element in a list.
E removeFirst()
It removes and returns the first element from a list.
boolean removeFirstOccurrence(Object o)
It is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail).
E removeLast()
It removes and returns the last element from a list.
boolean removeLastOccurrence(Object o)
It removes the last occurrence of the specified element in a list (when traversing the list from head to tail).
E set(int index, E element)
It replaces the element at the specified position in a list with the specified element.
Object[] toArray()
It is used to return an array containing all the elements in a list in proper sequence (from first to the last element).
<T> T[] toArray(T[] a)
It returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array.
int size()
It is used to return the number of elements in a list.
Java Deque Interface is a linear collection that supports element insertion and removal at both ends. Deque is an acronym for “double ended queue”.
boolean add(object)
It is used to insert the specified element into this deque and return true upon success.
boolean offer(object)
It is used to insert the specified element into this deque.
Object remove()
It is used to retrieves and removes the head of this deque.
Object poll()
It is used to retrieves and removes the head of this deque, or returns null if this deque is empty.
Object element()
It is used to retrieves, but does not remove, the head of this deque.
Object peek()
It is used to retrieves, but does not remove, the head of this deque, or returns null if this deque is empty.
The ArrayDeque class provides the facility of using deque and resizable-array. It inherits AbstractCollection class and implements the Deque interface.
The important points about ArrayDeque class are:
Unlike Queue, we can add or remove elements from both sides.
Null elements are not allowed in the ArrayDeque.
ArrayDeque is not thread safe, in the absence of external synchronization.
ArrayDeque has no capacity restrictions.
ArrayDeque is faster than LinkedList and Stack.
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It inherits the HashSet class and implements the Set interface.
The important points about the Java LinkedHashSet class are:
Java LinkedHashSet class contains unique elements only like HashSet.
Java LinkedHashSet class provides all optional set operations and permits null elements.
Java LinkedHashSet class is non-synchronized.
Java LinkedHashSet class maintains insertion order.
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
HashSet stores the elements by using a mechanism called hashing.
HashSet contains unique elements only.
HashSet allows null value.
HashSet class is non synchronized.
HashSet doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
HashSet is the best approach for search operations.
The initial default capacity of HashSet is 16, and the load factor is 0.75.
Various methods of Java HashSet class are as follows:
1)
boolean
It is used to add the specified element to this set if it is not already present.
2)
void
It is used to remove all of the elements from the set.
3)
object
It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
4)
boolean
It is used to return true if this set contains the specified element.
5)
boolean
It is used to return true if this set contains no elements.
6)
Iterator<E>
It is used to return an iterator over the elements in this set.
7)
boolean
It is used to remove the specified element from this set if it is present.
8)
int
It is used to return the number of elements in the set.
9)
Spliterator<E>
It is used to create a late-binding and fail-fast Spliterator over the elements in the set.
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.
The important points about the Java TreeSet class are:
Java TreeSet class contains unique elements only like HashSet.
Java TreeSet class access and retrieval times are quiet fast.
Java TreeSet class doesn’t allow null element.
Java TreeSet class is non synchronized.
Java TreeSet class maintains ascending order.
Java TreeSet class contains unique elements only like HashSet.
Java TreeSet class access and retrieval times are quite fast.
Java TreeSet class doesn’t allow null elements.
Java TreeSet class is non-synchronized.
Java TreeSet class maintains ascending order.
The TreeSet can only allow those generic types that are comparable. For example The Comparable interface is being implemented by the StringBuffer class.
boolean add(E e)
It is used to add the specified element to this set if it is not already present.
boolean addAll(Collection<? extends E> c)
It is used to add all of the elements in the specified collection to this set.
E ceiling(E e)
It returns the equal or closest greatest element of the specified element from the set, or null there is no such element.
Comparator<? super E> comparator()
It returns a comparator that arranges elements in order.
Iterator descendingIterator()
It is used to iterate the elements in descending order.
NavigableSet descendingSet()
It returns the elements in reverse order.
E floor(E e)
It returns the equal or closest least element of the specified element from the set, or null there is no such element.
SortedSet headSet(E toElement)
It returns the group of elements that are less than the specified element.
NavigableSet headSet(E toElement, boolean inclusive)
It returns the group of elements that are less than or equal to(if, inclusive is true) the specified element.
E higher(E e)
It returns the closest greatest element of the specified element from the set, or null there is no such element.
Iterator iterator()
It is used to iterate the elements in ascending order.
E lower(E e)
It returns the closest least element of the specified element from the set, or null there is no such element.
E pollFirst()
It is used to retrieve and remove the lowest(first) element.
E pollLast()
It is used to retrieve and remove the highest(last) element.
Spliterator spliterator()
It is used to create a late-binding and fail-fast spliterator over the elements.
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
It returns a set of elements that lie between the given range.
SortedSet subSet(E fromElement, E toElement))
It returns a set of elements that lie between the given range which includes fromElement and excludes toElement.
SortedSet tailSet(E fromElement)
It returns a set of elements that are greater than or equal to the specified element.
NavigableSet tailSet(E fromElement, boolean inclusive)
It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element.
boolean contains(Object o)
It returns true if this set contains the specified element.
boolean isEmpty()
It returns true if this set contains no elements.
boolean remove(Object o)
It is used to remove the specified element from this set if it is present.
void clear()
It is used to remove all of the elements from this set.
Object clone()
It returns a shallow copy of this TreeSet instance.
E first()
It returns the first (lowest) element currently in this sorted set.
E last()
It returns the last (highest) element currently in this sorted set.
int size()
It returns the number of elements in this set.
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface.
Java LinkedHashMap contains values based on the key.
Java LinkedHashMap contains unique elements.
Java LinkedHashMap may have one null key and multiple null values.
Java LinkedHashMap is non synchronized.
Java LinkedHashMap maintains insertion order.
The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
V get(Object key)
It returns the value to which the specified key is mapped.
void clear()
It removes all the key-value pairs from a map.
boolean containsValue(Object value)
It returns true if the map maps one or more keys to the specified value.
Set<Map.Entry<K,V>> entrySet()
It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer<? super K,? super V> action)
It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue)
It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key.
Set<K> keySet()
It returns a Set view of the keys contained in the map
protected boolean removeEldestEntry(Map.Entry<K,V> eldest)
It returns true on removing its eldest entry.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)
It replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection<V> values()
It returns a Collection view of the values contained in this map.
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order.
The important points about Java TreeMap class are:
Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
Java TreeMap contains only unique elements.
Java TreeMap cannot have a null key but can have multiple null values.
Java TreeMap is non synchronized.
Java TreeMap maintains ascending order.
Character
关于split 的转义字符 以下参考