521. Longest Uncommon Subsequence I
find the longest uncommon subsequence of this group of two strings
解题思路:
因为求的是最长uncommon subsequence的长度,所以,如果ab长度不等,应返回长度较大值;ab相同,则返回-1;否则返回长度即可。
int findLUSlength(string a, string b) { if (a == b) return -1; if (a.size() != b.size()) return a.size() > b.size() ? a.size() : b.size(); return a.size(); }
392. Is Subsequence
Given a string s and a string t, check if s is subsequence of t.
解题思路:直接扫一遍t检查就好了。。注意,如果s已经找完,应该跳出循环,不然会runtime error
bool isSubsequence(string s, string t) { int i, j; for (i = 0, j = 0; i < t.length(); i++) { if (j == s.length()) break; if (t[i] == s[j]) j++; } return j == s.length(); }
541. Reverse String II
解题思路:
其实是以2k为一组,翻转前i个(i<=k)。所以对于长度为2k的正常翻转,最后一组考虑长度<k的情况。另外,对于k>s.length()时,要翻转
整个s。
string reverseStr(string s, int k) { if (s.length() < 2 || k == 0 ) return s; string result = s; bool flag = false; int i; if (s.length() <= k) { flag = true; i = 0; } //int i; if (flag == false) { for (i = 0; i < s.length(); i = i + 2 * k) { int m = i; int n = i + k - 1; if (n >= s.length()) { flag = true; break; } int temp; while (m <= n) { temp = result[m]; result[m] = result[n]; result[n] = temp; m ++; n --; } } } if (flag == true) { int m = i; int n = s.length()-1; int temp; while (m <= n) { temp = result[m]; result[m] = result[n]; result[n] = temp; m ++; n --; } } return result; }
时间: 2024-11-08 08:08:14