练习题1:字符串最后一个单词的长度
int main()
{
string str;
getline(cin,str);
size_t pos = str.rfind(' ');
if (pos != string::npos)
{
cout<< str.size()-pos-1 <<endl;
}
else
{
cout<< str.size() <<endl;
}
return 0;
}
练习题2:字符串中的第一个唯一字符(思想:计数排序)
class Solution
{
public:
static int firstUniqChar(string s)
{
int countArr[26] = { 0 };
for (auto ch : s)
{
countArr[ch - 'a']++;
}
for (size_t i = 0; i < s.size(); ++i)
{
if (countArr[s[i] - 'a'] == 1)
return i;
}
return -1;
}
};
int main()
{
string s1("belho,werld");
cout << Solution::firstUniqChar(s1) << endl;
return 0;
}
练习题3、验证回文串
class Solution
{
public:
static bool isLetterOrNumber(char ch)
{
return(ch >= '0' && ch <= '9')
|| (ch >= 'a' && ch <= 'z');
}
static 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])
{
++begin;
--end;
}
else
{
return false;
}
}
return true;
}
};
int main()
{
string s1 = "hello , ollEH";
cout << Solution::isPalindrome(s1) << endl;
return 0;
}