码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】字符串 string(共112题)

时间:2018-12-04 13:25:04      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:通过   alt   regular   nim   output   back   parse   char   ica   

【3】Longest Substring Without Repeating Characters 

【5】Longest Palindromic Substring 

【6】ZigZag Conversion 

【8】String to Integer (atoi) 

【10】Regular Expression Matching 

【12】Integer to Roman 

【13】Roman to Integer 

【14】Longest Common Prefix 

【17】Letter Combinations of a Phone Number 

【20】Valid Parentheses 

【22】Generate Parentheses 

 

【28】Implement strStr()  (算法群,2018年11月4日,练习kmp)

实现在字符串 s 中找到 模式串 p, (kmp)

题解:暴力O(N*M) 可以解, kmp O(N+M) 也可以解 ,kmp务必再深入理解一下 next 数组的求法。不然面试不给笔记看就凉凉了。(还有一个注意点是 p 为空串的时候要特判)

技术分享图片
 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         return kmp(haystack, needle);
 5     }
 6     int kmp(string& s, string& p) {
 7         const int n = s.size(), m = p.size();
 8         if (m == 0) {return 0;} //p empty
 9         vector<int> next = getNext(p);
10         int i = 0, j = 0;
11         while (i < n && j < m) {
12             if (j == -1 || s[i] == p[j]) {
13                 ++i, ++j;
14             } else {
15                 j = next[j];
16             }
17         }
18         if (j == m) {
19             return i - j;
20         }
21         return -1;
22     }
23     vector<int> getNext(string& p) {
24         const int n = p.size();
25         vector<int> next(n, 0);
26         next[0] = -1;
27         int j = 0, k = -1;
28         while (j < n - 1) {
29             if (k == -1 || p[j] == p[k]) {
30                 ++k, ++j;
31                 next[j] = p[j] == p[k] ? next[k] : k;
32             } else {
33                 k = next[k];
34             }
35         }
36         return next;
37     }
38 };
kmp
技术分享图片
 1 //暴力解法 O(N*M)
 2 class Solution {
 3 public:
 4     int strStr(string haystack, string needle) {
 5         const int n = haystack.size(), m = needle.size();
 6         if (m == 0) {return 0;}
 7         for (int i = 0; i + m <= n; ) {  // 判断条件要不要取等号,然后下面做了++i, ++j, for循环里面就别做了,尴尬,这都能错
 8             int j; int oldi = i;
 9             for (j = 0; j < m;) {
10                 if (haystack[i] == needle[j]) {
11                     ++i, ++j;
12                 } else {
13                     break;
14                 }
15             }
16             if (j == m) {
17                 return i - j;
18             } else {
19                 i = oldi + 1;
20             }
21         }
22         return -1;
23     }
24 };
暴力

 

【30】Substring with Concatenation of All Words 

【32】Longest Valid Parentheses 

【38】Count and Say 

 

【43】Multiply Strings (2018年11月27日,高精度乘法)

给了两个string类型的数字,num1 和 num2, 用string的形式返回 num1 * num2。(num1, num2 的长度都小于等于110)

题解:num3 = num1 * num2, num3 最大的长度为 num1.size() + num2.size()。先翻转 num1, num2, 翻转以后从前往后乘。可能最后结果有前置0,把前置 0 去除。 

技术分享图片
 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         size1 = num1.size(), size2 = num2.size();
 5         v1 = str2vecAndReverse(num1), v2 = str2vecAndReverse(num2);
 6         vector<int> v3(size1 + size2, 0);
 7         for (int i = 0; i < size1; ++i) {
 8             for (int j = 0 ; j < size2; ++j) {
 9                 v3[i+j] += v1[i] * v2[j];
10                 v3[i+j+1] += v3[i+j] / 10;
11                 v3[i+j] = v3[i+j] % 10;
12             }
13         }
14         string ret = "";
15         for (auto n : v3) {
16             ret = to_string(n) + ret;
17         }
18         auto p = ret.find_first_not_of(0);
19         if (p == string::npos) {
20             ret = "0";
21         } else {
22             ret = ret.substr(p);
23         } 
24         return ret;
25     }
26     vector<int> str2vecAndReverse(string num) {
27         int size = num.size();
28         vector<int> ret(size);
29         for (int i = size - 1; i >= 0; --i) {
30             ret[size-i-1] = num[i] - 0;
31         }
32         return ret;
33     }
34     int size1 = 0, size2 = 0;
35     vector<int> v1, v2;
36 };
View Code

  

【44】Wildcard Matching 

【49】Group Anagrams 

【58】Length of Last Word 

【65】Valid Number 

【67】Add Binary 

【68】Text Justification 

【71】Simplify Path 

【72】Edit Distance 

【76】Minimum Window Substring 

【87】Scramble String 

【91】Decode Ways 

【93】Restore IP Addresses 

【97】Interleaving String 

【115】Distinct Subsequences 

【125】Valid Palindrome 

【126】Word Ladder II 

【151】Reverse Words in a String (2018年11月8日, 原地翻转字符串)

 

【157】Read N Characters Given Read4 

【158】Read N Characters Given Read4 II - Call multiple times 

【159】Longest Substring with At Most Two Distinct Characters 

 

【161】One Edit Distance (2018年11月24日,刷题数)

给了两个字符串 s 和 t,问 s 能不能通过 增加一个字符, 删除一个字符,替换一个字符 这三种操作里面的任意一个变成 t。能的话返回 true, 不能的话返回 false。

题解:感觉是基础版的编辑距离。直接通过模拟来做。beats 36%。时间复杂度是 O(N).

技术分享图片
 1 class Solution {
 2 public:
 3     bool isOneEditDistance(string s, string t) {
 4         if (s == t) {return false;}
 5         const int ssize = s.size(), tsize = t.size();
 6         int cnt = 0;
 7         if (ssize == tsize) { //check replace;
 8             int idx = findfirstidx(s, t);
 9             if (idx == ssize || s.substr(idx+1) == t.substr(idx+1)) {
10                 return true;
11             }
12         } else if (ssize == tsize - 1) { //check insert
13             int idx = findfirstidx(s, t);
14             if (idx == tsize || s.substr(idx) == t.substr(idx+1)) {
15                 return true;
16             }
17             
18         } else if (ssize == tsize + 1){ //check delete
19             int idx = findfirstidx(s, t);
20             if (idx == ssize || s.substr(idx+1) == t.substr(idx)) {
21                 return true;
22             }
23         }
24         return false;
25     }
26     inline int findfirstidx (string s, string t) {
27         const int ssize = s.size(), tsize = t.size();
28         int tot = min(ssize, tsize);
29         for (int i = 0; i < tot; ++i) {
30             if (s[i] != t[i]) {
31                 return i;
32             }
33         }
34         return max(ssize, tsize);
35     }
36 };
View Code

 

【165】Compare Version Numbers 

 

【186】Reverse Words in a String II (2018年11月8日, 原地翻转字符串)

Given an input string , reverse the string word by word. 

Example:
Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note: 
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.

题解:无。

技术分享图片
 1 class Solution {
 2 public:
 3     void reverseWords(vector<char>& str) {
 4         reverse(str.begin(), str.end());
 5         const int n = str.size();
 6         int p1 = 0, p2 = 0;
 7         while (p2 < n) {
 8             while (p1 < n && str[p1] ==  ) {p1++;}
 9             p2 = p1;
10             while (p2 < n && str[p2] !=  ) {p2++;}
11             reverse(str.begin() + p1, str.begin() + p2);
12             p1 = p2;
13         }
14         return;
15     }
16 };
View Code

 

【214】Shortest Palindrome (2018年11月2日,周五,算法群)

给了一个字符串 S,为了使得 S 变成回文串可以在前面增加字符,在增加最少的字符的前提下返回新的回文 S。

题解:我的做法跟昨天的题一样(366)就是找从第一个字符开始最长的回文串,然后把后面的那小段翻转一下,拼到前面。时间复杂度是O(N^2)

技术分享图片
 1 //类似的题目可以见 336 Palindrome Pairs
 2 class Solution {
 3 public:
 4     string shortestPalindrome(string s) {
 5         const int n = s.size();
 6         string ans = "";
 7         for (int j = n; j >= 0; --j) {
 8             if (isPalindrome(s, 0, j-1)) {
 9                 string str = s.substr(j);
10                 reverse(str.begin(), str.end());
11                 ans = str + s;
12                 break;
13             }
14         }
15         return ans;
16     }
17     bool isPalindrome(const string& s, int start, int end) { //[start, end]
18         while (start < end) {
19             if (s[start] != s[end]) {return false;}
20             start++, end--;
21         }
22         return true;
23     }
24 };
View Code

应该还有更好的解法:(学习学习学习)。

【227】Basic Calculator II 

【249】Group Shifted Strings 

【271】Encode and Decode Strings 

【273】Integer to English Words 

【293】Flip Game 

【336】Palindrome Pairs (2018年11月1日,周四,算法群)

给了一组字符串words,找出所有的pair (i,j),使得 words[i] + words[j] 这个新的字符串是回文串。

题解:这题WA出了天际。因为map似乎一旦访问了某个不存在的key,这个key就变的存在了。。一开始我想暴力,暴力超时,暴力时间的时间复杂度是O(N^2*K)。后来认真思考了一下一个字符串是怎么变成回文的。如果一个字符串word,他的长度是n,如果它的前半段 word[0..j] 是个回文串,那么我们需要匹配它后面那段 word[j+1..n-1], 我们把后半段reverse一下, 查找字符串集合(map)里面有没有对应的这段。同理,如果它的后半段 word[j+1..n-1] 是个回文串,那么我们把前半段 reverse一下,在 map 里面查找有没有前半段就可以了。特别注意这个前半段和后半段都可以包含空串,所以 j 的范围是[0, n]。

技术分享图片
 1 class Solution {
 2 public:
 3     vector<vector<int>> palindromePairs(vector<string>& words) {
 4         const int n = words.size();
 5         unordered_map<string, int> mp;
 6         for (int i = 0; i < n; ++i) {
 7             mp[words[i]] = i;
 8         }
 9         vector<vector<int>> ans;
10         set<vector<int>> st;
11         for (int i = 0; i < n; ++i) {
12             string word = words[i];
13             int size = word.size();
14             for (int j = 0; j <= size; ++j) {
15                 if (isPalindrome(word, 0, j-1)) {
16                     string str = word.substr(j);
17                     reverse(str.begin(), str.end());
18                     //vector<int> candidate = vector<int>{mp[str], i};  这个不能放在外面,不然mp[str]可能不存在
19                     if (mp.find(str) != mp.end() && mp[str] != i) {
20                         vector<int> candidate = vector<int>{mp[str], i};
21                         if (st.find(candidate) == st.end()) {
22                             ans.push_back(candidate);
23                             st.insert(candidate);
24                         }
25                     }
26                 }
27                 if (isPalindrome(word, j, size-1)) {
28                     string str = word.substr(0, j);
29                     reverse(str.begin(), str.end());
30                     //vector<int> candidate = vector<int>{i, mp[str]};
31                     if (mp.find(str) != mp.end() && mp[str] != i) {
32                         vector<int> candidate = vector<int>{i, mp[str]};
33                         if (st.find(candidate) == st.end()) {
34                             ans.push_back(candidate);
35                             st.insert(candidate);
36                         }
37                     }
38                 }
39             }
40         }
41         return ans;
42     }
43     bool isPalindrome(const string& word, int start, int end) { // [start, end]
44         while (start < end) {
45             if (word[start++] != word[end--]) { return false; }
46         }   
47         return true;
48     }
49 };
View Code

 听说这题还能用 trie 解,有空要看答案啊。

 

【340】Longest Substring with At Most K Distinct Characters 

 

【344】Reverse String (2018年12月3日,第一次review,ko)

逆序一个字符串。

题解:直接reverse,或者 2 pointers

技术分享图片
 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         int start = 0, end = s.size() - 1;
 5         while (start < end) {
 6             swap(s[start++], s[end--]);
 7         }
 8         return s;
 9     }
10 };
View Code

 

【345】Reverse Vowels of a String (2018年12月4日,第一次review,ko)

 

逆序一个字符串的元音字母。

题解:2 pointers

技术分享图片
 1 class Solution {
 2 public:
 3     string reverseVowels(string s) {
 4         set<char> setVowels = {a, e, i, o, u, A, E, I, O, U};
 5         int left = 0, right = s.size()-1;
 6         while (left < right) {
 7             while (setVowels.find(s[left]) == setVowels.end()) {++left;}
 8             while (setVowels.find(s[right]) == setVowels.end()) {--right;}
 9             if (left < right) { //这里需要再次判断
10                 swap(s[left++], s[right--]);
11             }
12         }
13         return s;
14     }
15 };
View Code

 

 

【383】Ransom Note 

【385】Mini Parser 

【387】First Unique Character in a String 

【408】Valid Word Abbreviation 

【434】Number of Segments in a String 

【443】String Compression 

【459】Repeated Substring Pattern 

【468】Validate IP Address 

【520】Detect Capital 

【521】Longest Uncommon Subsequence I 

【522】Longest Uncommon Subsequence II 

【527】Word Abbreviation 

【536】Construct Binary Tree from String 

 

【537】Complex Number Multiplication (2018年11月27日)

给了两个字符串,代表两个 complex, 返回这两个complex 的乘积(用字符串表示)。

题解:见math分类:https://www.cnblogs.com/zhangwanying/p/9790007.html

 

【539】Minimum Time Difference 

【541】Reverse String II 

【544】Output Contest Matches 

【551】Student Attendance Record I 

【553】Optimal Division 

【555】Split Concatenated Strings 

【556】Next Greater Element III 

【557】Reverse Words in a String III 

【564】Find the Closest Palindrome 

【583】Delete Operation for Two Strings 

【591】Tag Validator 

 

【606】Construct String from Binary Tree 

2018年11月14日,树的分类里面做了:https://www.cnblogs.com/zhangwanying/p/6753328.html

 

【609】Find Duplicate File in System 

【616】Add Bold Tag in String 

【632】Smallest Range 

【635】Design Log Storage System 

【647】Palindromic Substrings 

【657】Robot Return to Origin 

【678】Valid Parenthesis String 

【680】Valid Palindrome II 

【681】Next Closest Time 

【686】Repeated String Match 

【696】Count Binary Substrings 

【709】To Lower Case 

【722】Remove Comments 

【730】Count Different Palindromic Subsequences 

【736】Parse Lisp Expression 

【758】Bold Words in String 

【761】Special Binary String 

【767】Reorganize String 

【770】Basic Calculator IV 

【772】Basic Calculator III 

【788】Rotated Digits 

 

【791】Custom Sort String (2018年11月27日)

给了两个字符串 S 和 T, S中最多有 26个小写字母,给 T 重新排序,如果字母 x, y 在 S 中出现,且在 T 中出现,如果在 S 中 x 出现在 y 之前, 那么在 T 中 x 也要出现在 y 之前。没有在 S 中出现的字符就随便放哪里都可以。

题解:直接 unordered_map

技术分享图片
 1 class Solution {
 2 public:
 3     string customSortString(string S, string T) {
 4         const int n = T.size();
 5         unordered_map<char, int> mp;
 6         for (int i = 0; i < n; ++i) {
 7             mp[T[i]]++;
 8         }
 9         string ret;
10         for (auto c : S) {
11             if (mp.find(c) == mp.end() || mp[c] == 0) {continue;}
12             ret += string(mp[c], c);
13             mp[c] = 0;
14         }
15         for (auto ele : mp) {
16             if (ele.second > 0) {
17                 ret += string(ele.second, ele.first);
18             }
19         }
20         return ret;
21     }
22 };
View Code

 

【800】Similar RGB Color 

【804】Unique Morse Code Words 

【809】Expressive Words 

【816】Ambiguous Coordinates 

【819】Most Common Word 

【824】Goat Latin 

【831】Masking Personal Information 

【833】Find And Replace in String 

【842】Split Array into Fibonacci Sequence 

【848】Shifting Letters 

【856】Score of Parentheses 

【859】Buddy Strings 

【890】Find and Replace Pattern 

【893】Groups of Special-Equivalent Strings 

【899】Orderly Queue 

【LeetCode】字符串 string(共112题)

标签:通过   alt   regular   nim   output   back   parse   char   ica   

原文地址:https://www.cnblogs.com/zhangwanying/p/9885334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!