这次选了2题easy难度的题和1道normal难度的题。
2题easy都是关于字符串处理的,有相似之处所以一起写出来,加以对比。
389. Find the Difference
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
这里只需要最简单的方法就可以了,因为t只多了一个字母,把t每个字母找s中相同的字母,找到后删除s中此字母。若找不到则直接输出此字母。
class Solution {
public:
char findTheDifference(string s, string t) {
int lenn=t.size(),lenm=s.size();
for(int i=0;i<lenn;i++){
bool find=0;
for(int j=0;j<lenm;j++){
if(t[i]==s[j]){find=1;s[j]=0;break;}
}
if(!find)return t[i];
}
return t[0];
}
};
383. Ransom Note
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
这道题跟上一道非常相似,区别就是字母不只是差一个,然而这继续用之前的算法也是没问题的,只需要修改返回的值就可以了。class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int lenn=ransomNote.size(),lenm=magazine.size();
if(lenn>lenm)return false;
else{
for(int i=0;i<lenn;i++){
bool find=0;
for(int j=0;j<lenm;j++){
if(ransomNote[i]==magazine[j]){find=1;magazine[j]=0;break;}
}
if(!find)return false;
}
return true;
}
}
};
238. Product of Array Except Self
Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements ofnums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> prob,out;
int f2b=1,b2f=1,len=nums.size();
prob.push_back(f2b);
for(int i=1;i<len;i++){
f2b *= nums[len-i];
prob.push_back(f2b);
}
out.push_back(prob[len-1]);
for(int i=1;i<len;i++){
b2f *= nums[i-1];
out.push_back(b2f*prob[len-i-1]);
}
return out;
}
};