LeetCode 87. Scramble String
bool isScramble(string s1, string s2) {
if(s1 == s2) return true;
int counter[26] = {0}, len = s1.size();
for(int i = 0; i < len; i++) {
counter[s1[i]-'a']++;
counter[s2[i]-'a']--;
}
for(int i = 0; i < 26; i++)
if(counter[i] != 0)
return false;
for(int i = 1; i < len; i++) {
if(isScramble(s1.substr(0, i), s2.substr(0, i))
&& isScramble(s1.substr(i), s2.substr(i)))
return true;
if(isScramble(s1.substr(0, i), s2.substr(len-i))
&& isScramble(s1.substr(i), s2.substr(0, len-i)))
return true;
}
return false;
}
思路:这种类似于树状的题目一般用递归,步骤为1.检查是否相等,2.检查是否为异构体,3.递归检查是否符合交换的条件
LeetCode 179. Largest Number
static bool cmp(int x, int y) {
string s1 = to_string(x);
string s2 = to_string(y);
return s1+s2 > s2+s1;
}
string largestNumber(vector& nums) {
sort(nums.begin(), nums.end(), cmp);
string res = "";
for(int i = 0; i < nums.size(); i++)
res += to_string(nums[i]);
if(res.size() == 0) return "";
if(res[0] == '0') return "0";
return res;
}
思路:数字字符串比较大小,return s1+s2>s2+s1;
LeetCode 6.ZigZag Conversion
string convert(string s, int numRows) {
if(numRows == 1) return s;
int T = (numRows-1)*2;
string res = "";
for(int i = 0; i < numRows; i++) {
int index = i, step = (numRows-1-i)*2;
while(index < s.size()) {
if(index < s.size())
res += s[index];
if(step != 0 && step != T && index + step < s.size())
res += s[index+step];
index += T;
}
}
return res;
}
思路:找规律,逐个字符加起来即可。
LeetCode 38. Count and Say
string countAndSay(int n) {
string res = "1";
while(--n) {
char ch = res[0];
int count = 0;
string cur = "";
for(int i = 0; i < res.size(); i++) {
if(ch == res[i])
count++;
else {
cur += to_string(count) + ch;
ch = res[i], count = 1;
}
}
cur += to_string(count) + ch;
res = cur;
}
return res;
}
思路:按照题目说明迭代即可
LeetCode 316. Remove Duplicate Letters
string removeDuplicateLetters(string s) {
int counter[26] = {0};
bool exist[26] = {0};
stack st;
for(int i = 0; i < s.size(); i++)
counter[s[i]-'a']++;
for(int i = 0; i < s.size(); i++) {
int index = s[i]-'a';
counter[index]--;
if(exist[index])
continue;
while(!st.empty() && s[i] < st.top() && counter[st.top()-'a'] > 0) {
exist[st.top()-'a'] = false;
st.pop();
}
st.push(s[i]);
exist[index] = true;
}
string res = "";
while(!st.empty()) {
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
思路:逐个检查是否在栈中,若不在栈中且比栈顶元素都要小,且栈顶元素在后续的字符串中存在,则将该栈顶元素弹出。最后逐个加起来并逆序即可。
LeetCode 168. Excel Sheet Column Title
string convertToTitle(int n) {
string res = "";
while(n > 0) {
res = char((n - 1)%26 + 'A') + res;
n = (n - (n - 1) % 26 - 1) / 26;
}
return res;
}
思路:题目的意思很清楚,主要问题在于不是从0开始的,这点比较麻烦。
string convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(n / 26) + (char) (--n % 26 + 'A');
}
一行代码版本
LeetCode 171. Excel Sheet Column Number
int titleToNumber(string s) {
long long res = 0, base = 1;
for(int i = s.size()-1; i >= 0; i--) {
res += (s[i]-'A'+1)*base;
base *= 26;
}
return res;
}
注意:base会超出 int 的范围,要用 long long
LeetCode 13. Roman to Integer
def romanToInt(self, s):
dic = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
cur, res = 'I', 0
for c in s[::-1]:
if dic[c] >= dic[cur]:
res += dic[c]
else:
res -= dic[c]
cur = c
return res
LeetCode 12. Integer to Roman
def intToRoman(self, num):
values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ]
numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ]
# 迭代依次处理每位数字
res, i = "", 0
while num:
res += (num//values[i]) * numerals[i]
num %= values[i]
i += 1
return res
LeetCode 273. Integer to English Words
class Solution:
def numberToWords(self, num: 'int') -> 'str':
UNIT = ['Hundred', 'Thousand', 'Million', 'Billion']
SHI = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
GE = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
SHIJI = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
if num == 0: return "Zero"
num = str(num)[::-1]
length, i = len(num), 0
words = []
while i < length:
if i+1 < length:
if num[i+1] != '1':
if num[i] != '0':
words.append(GE[int(num[i])])
if num[i+1] != '0':
words.append(SHI[int(num[i+1])])
else:
words.append(SHIJI[int(num[i])])
elif num[i] != '0':
words.append(GE[int(num[i])])
break
if i+2 < length and num[i+2] != '0':
words.append(UNIT[0])
words.append(GE[int(num[i+2])])
for j in [3, 4, 5]:
if i+j < length and num[i+j] != '0':
words.append(UNIT[(i+3)//3])
break
i += 3
res = " "
return res.join(words[::-1])
Python版本
string belowTen[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
string belowTwenty[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
string belowHundred[] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string & trim(string &s) {
if (s.empty())
return s;
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
string helper(int num) {
string result;
if(num < 10) result = belowTen[num];
else if(num < 20) result = belowTwenty[num - 10];
else if(num < 1e2) result = belowHundred[num / 10] + " " + helper(num % 10);
else if(num < 1e3) result = helper(num / int(1e2)) + " Hundred " + helper(num % int(1e2));
else if(num < 1e6) result = helper(num / int(1e3)) + " Thousand " + helper(num % int(1e3));
else if(num < 1e9) result = helper(num / int(1e6)) + " Million " + helper(num % int(1e6));
else result = helper(num / int(1e9)) + " Billion " + helper(num % int(1e9));
return trim(result);
}
string numberToWords(int num) {
if(num == 0) return "Zero";
return helper(num);
}
C++版本,使用trim()函数,作用和Python中的strip()相同,去除首尾的多余空格。
824. Goat Latin
def toGoatLatin(self, S: 'str') -> 'str':
if not S: return S
words = S.split()
vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
ass = 'a'
for i in range(len(words)):
if words[i][0] not in vowels:
words[i] = words[i][1:] + words[i][0] + 'ma' + ass
else:
words[i] = words[i] + 'ma' + ass
ass += 'a'
res = " "
return res.join(words).strip()
思路:简单字符串处理