题目一 ,把字符串转换成整数
class Solution {
public:
int StrToInt(string str)
{
int flag = 1, sum = 0, k = 0;
if(str[0] == '-')
flag = -1;
for(int i = str.size()-1; i >= 0; i--)
{
if(i == 0 && (str[i] == '+' || str[i] == '-') )
continue;
if('0' <= str[i] && str[i] <= '9')
{
sum += pow(10,k) * (str[i] - '0');
k++;
}
else
{
return 0;
}
}
return sum * flag;
}
};
解题思路和题目分析
题目2,力扣415. 字符串相加
class Solution {
public:
string addStrings(string num1, string num2)
{
string str;
int index = 0, end1 = num1.size()-1, end2 = num2.size()-1;
while(end1 >= 0 || end2 >=0 ) //从后向前遍历,然后存在一个就必须还要计算
{
int ret1 = 0, ret2 = 0;
if(end1 >= 0)
ret1 = num1[end1] - '0';
if(end2 >= 0)
ret2 = num2[end2] - '0';
int ret = ret1 + ret2 + index;
index = 0;
str.insert(0,1,'0' + ret % 10);
if(ret >= 10)
{
index = 1;
}
end1--;
end2--;
}
if(index == 1)
str.insert(0,1,'0' + index);
return str;
}
};
题目3,力扣917,仅仅反转字母
class Solution {
public:
bool isupperorsamll(char c)
{
return (('a' <= c && c <= 'z' ) ||
('A' <= c && c <= 'Z'));
}
string reverseOnlyLetters(string s)
{
int left = 0 , right = s.size()-1;
while(left < right)
{
while(left < right && !isupperorsamll(s[left]))
left++;
while(left < right && !isupperorsamll(s[right]))
right--;
swap(s[left],s[right]);
left++;
right--;
}
return s;
}
};
题目4—力扣387. 字符串中的第一个唯一字符
用的是映射法
class Solution {
public:
int firstUniqChar(string s)
{
int counts[26] = {0}, i = 0;
for(i= 0; i < s.size(); i++)
{
counts[s[i] - 'a']++; //向数组里面填数据出现的次数
}
for(i = 0; i < s.size(); i++)
{
if(counts[s[i] - 'a'] == 1) //取次数的时候只能从字符串0的位置开始
return i;
}
return -1;
}
};