To convert list into string in Python. Simply use "".join(str). This will make '' between every single chars.
9. Palindrome Number
# String
C++11 introduces std::stoi (and variants for each numeric type) and std::to_string,
the counterparts of the C atoi and itoa but expressed in term of std::string.
When choosing convert int to string in C++, simply #include <string> and call it to handle variant length string!
A pure math implementation is:
12. Integer to Roman
C++ 里的map底层是用类似红黑树的方式存的,默认按照key排序,而且不能直接调用sort函数对value排序。
如果一定要按value排序,该怎么做呢!
Besides, use for(auto & it : vec) to traverse the vector elegantly.
1
Dynamic Programming
Intuition
As the problem has an optimal substructure, it is natural to cache intermediate results. We ask the question \text{dp(i, j)}dp(i, j): does \text{text[i:]}text[i:] and \text{pattern[j:]}pattern[j:] match? We can describe our answer in terms of answers to questions involving smaller strings.
Longest Common Substring
For completeness, difflib in the standard-library provides loads of sequence-comparison utilities.
For instance find_longest_match which finds the longest common substring when used on strings.
Example use:
12. Integer to Roman
The only pratical way to convert queue to vector:
15. 3Sum
Classic! Fix 1 pointer then move the rest 2 pointers.
empty - Test whether container is empty (public member function )
size - Return size (public member function )
top - Access top element (public member function )
push - Insert element (public member function )
emplace - Construct and insert element (public member function )
pop - Remove top element (public member function )
swap - Swap contents (public member function )
128. Longest Consecutive Sequence
Union Find / Hash Set
Use s.find() to search elem in set.
136. Single Number
Bit Manipulation / Hash Map
A XOR trick to solve this:
If we take XOR of zero and some bit, it will return that bit
a⊕0=a
If we take XOR of two same bits, it will return 0
a⊕a=0
And
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
So we can XOR(^in Python) all bits together to find the unique number.
338. Counting Bits
Bit Manipulation
Bitwise operator has the same priority with math ones.