面试题 01.01. 判定字符是否唯一
class Solution {
public:
bool isUnique(string astr) {
for(int i=0;i<astr.size();i++)
{
if(astr.find(astr[i])!=astr.rfind(astr[i]))
return false;
}
return true;
}
};
面试题 01.02. 判定是否互为字符重排
class Solution {
public:
bool CheckPermutation(string s1, string s2) {
sort(s1.begin(),s1.end());
sort(s2.begin(),s2.end());
if(s1==s2)
return true;
else return false;
}
};
面试题 01.03. URL化
class Solution {
public:
string replaceSpaces(string S, int length) {
string res;
for(int i=0;i<length;i++)
{
if(S[i]==' ')
res+="%20";
else res+=S[i];
}
return res;
}
};
面试题 01.04. 回文排列
申请一个map用于存储字符出现次数,如果排列能够构成回文串,那么字符串中出现奇数次的字符最多允许有1个
class Solution {
public:
bool canPermutePalindrome(string s) {
map<char,int>m;
int cnt=0;
for(int i=0;i<s.size();i++)
m[s[i]]++;
for(auto a=m.begin();a!=m.end();a++)
{
if(a->second%2==1) cnt++;
if(cnt>1)return false;
}
return true;
}
};
面试题 01.05. 一次编辑
首先判断两个字符串长度,相差大于一返回 false
双指针遍历两个字符串,同时记录编辑次数 op_cnt:
若 first[i] == second[j],不需编辑,i,j 加一
若 first[i] != second[j],分为三种情况:
first[i] == second[j+1],那么 j++,op_cnt++
first[i+1] == second[j],那么 i++,op_cnt++
以上两种都不符合,那么使用替换操作,i++,j++,op_cnt++
注意,一旦 op_cnt > 1,返回 false
遍历结束后,若仍有一方未走到结尾,且相差的长度 + op_cnt 大于 1,则返回 false。
class Solution {
public:
bool oneEditAway(string first, string second) {
int fl=first.size();
int sl=second.size();
if(abs(fl-sl)>=2) return false;
int i=0,j=0;
int cnt=0;
while(i<fl&&j<sl)
{
if(first[i]==second[j])
{
i++;j++;
}
else
{
if(first[i+1]==second[j])
{
i++;cnt++;
if(cnt>1)
return false;
}
else if(first[i]==second[j+1])
{
cnt++;j++;
if(cnt>1)
return false;
}
else{
i++;j++;cnt++;
if(cnt>1)
return false;
}
}
}
if(max(fl-i,sl-j)+cnt>1)return false;
return true;
}
};