OJ1-字符串的第一个唯一字符
思路:将字母看成他们各自对应的ASCII,例如A的ASCII为65,则每遇见一次A,就将A的次数加一,即将以65为下标的数组元素加一。
代码如下:
class Solution {
public:
int firstUniqChar(string s) {
// 统计每个字符出现的次数
int count[256] = {0};
int size = s.size();
for(int i = 0; i < size; ++i)
count[s[i]] += 1;
// 按照字符次序从前往后找只出现一次的字符
for(int i = 0; i < size; ++i)
if(1 == count[s[i]])
return i;
return -1;
}
};
OJ2-字符串最后一个单词的长度
代码如下:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string line;
// 不要使用cin>>line,因为会它遇到空格就结束了
// while(cin>>line)
while(getline(cin, line))
{
//size_t pos = line.rfind(' ');
//cout<<line.size()-pos-1<<endl;
//两种方法都可以,上面这个方法可以举个例子
//从后面往前找,找到第一个空格的位置,+1后为最后一个单词的第一个字母的位置。
cout<<line.substr(line.rfind(' ')+1).size()<<endl;
}
return 0;
}
OJ3-验证回文串
代码如下:
class Solution {
public:
bool isLetterOrNumber(char ch)
{
return (ch >= '0' && ch <= '9')|| (ch >= 'a' && ch <= 'z')|| (ch >= 'A' && ch <= 'Z');
}
bool isPalindrome(string s)
{
// 先小写字母转换成大写,再进行判断
for(auto& ch : s)
{
if(ch >= 'a' && ch <= 'z')
ch -= 32;
}
int begin = 0, end = s.size()-1;
while(begin < end)
{
while(begin < end && !isLetterOrNumber(s[begin]))
++begin;
while(begin < end && !isLetterOrNumber(s[end]))
--end;
if(s[begin] != s[end])
{
return false;
}
else
{
++begin;
--end;
}
}
return true;
}
};
OJ-4 字符串相加
#include<iostream>
using namespace std;
//1234 11
string stringSum(string s1, string s2)
{
int next = 0;
int begin1 = 0;
int begin2 = 0;
int end1 = s1.size() - 1;
int end2 = s2.size() - 1;
int value1 = 0, value2 = 0;
int temp = 0;
string res;
while (end1 >= 0 || end2 >= 0)
{
if (end1 >= 0)
{
value1 = s1[end1--]-'0';
}
else
{
value1 = 0;
}
if (end2 >= 0)
{
value2 = s2[end2--] - '0';
}
else
{
value2 = 0;
}
temp = value1+value2+next;
if (temp > 9)
{
next = 1;
temp -= 10;
}
else
{
next = 0;
}
res += (temp + '0');
}
if (next == 1)
{
res += '1';
}
reverse(res.begin(),res.end());
return res;
}
int main()
{
string s1 = "456";
string s2 = "77";
string res = stringSum(s1, s2);
cout << res << endl;
return 0;
}