[43] Multiply Strings
Given two non-negative integers
num1andnum2represented as strings, return the product ofnum1andnum2, also represented as a string.
算法答题思路就是模拟乘法累加的过程.
需要注意的是, js大数相加会丢失精度, 所以谨慎使用.
1 | /** |
[13] Roman to Integer
Roman numerals are represented by seven different symbols:
I,V,X,L,C,DandM.For example, two is written as
IIin Roman numeral, just two one’s added together. Twelve is written as,XII, which is simplyX+II. The number twenty seven is written asXXVII, which isXX+V+II.Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
时间复杂度: 遍历整个字符串, $O(N)$
空间复杂度: 常数级别.
1 | // 罗马数字一共三种情况 |
[12] Integer to Roman
Roman numerals are represented by seven different symbols:
I,V,X,L,C,DandM.For example, two is written as
IIin Roman numeral, just two one’s added together. Twelve is written as,XII, which is simplyX+II. The number twenty seven is written asXXVII, which isXX+V+II.
主要是不同数位的数字转换, 需要对数位进行分情况讨论. 不同数位的相同数字, 对应使用的罗马字符也不同.
1 | // 主要思路就是, 逐步整除, 然后对商进行对应数位的转换 |
[49] Group Anagrams
Given an array of strings
strs, group the anagrams together. You can return the answer in any order.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
1 | // 将字符串按照构成分组 |
[67] Add Binary
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters
1or0.
时间复杂度:
假设两个串的长度分别为M/N, 则时间复杂度为 $O(max(M, N))$.
1 | var addBinary = function (a, b) { |
[28] Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
时间复杂度:
设source长度为N, target长度为M, 最差的情况是: 一直遍历到最后的部分才知道是否有和target匹配的部分. O((N-M)*M). 不用遍历到source的最后一个元素, 只要剩余部分的长度不足M, 即可退出遍历.
1 | // 直观想法 使用双重循环 |