【LeetCode】917. 仅仅反转字母、387. 字符串中的第一个唯一字符

 作者:小卢 

专栏:《Leetcode》

喜欢的话:世间因为少年的挺身而出,而更加瑰丽。                                  ——《人民日报》


目录

 917. 仅仅反转字母

 387. 字符串中的第一个唯一字符


 917. 仅仅反转字母

917. 仅仅反转字母 

题目描述:

给你一个字符串 s ,根据下述规则反转字符串:

  • 所有非英文字母保留在原有位置。
  • 所有英文字母(小写或大写)位置反转。

返回反转后的 s 。

示例:

思路:

 利用两个指针来遍历字符串,一个指向头一个指向尾,两个指针找到是字母的位置,然后交换,直到begin==end。

代码:

class Solution {
public:
bool ischar(char ch)
{
    if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
    return true;
    return false;
}
    string reverseOnlyLetters(string s) {
        int begin=0;
        int end=s.size()-1;
        while(begin<end)
        {
            while(begin<end&&!ischar(s[begin]))
            begin++;
            while(begin<end&&!ischar(s[end]))
            end--;
            swap(s[begin],s[end]);
            begin++;
            end--;
        }
        return s;
    }
};

 387. 字符串中的第一个唯一字符

387. 字符串中的第一个唯一字符

题目描述:

给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。

示例:

思路:

利用一个计数数组Count[],变量字符串,在字母-‘a’的对应位置计数,最后在遍历一次字符串,找到第一个等于1的位置。 

代码:

class Solution {
public:
    int firstUniqChar(string s) {
        int Count[30]={0};
        for(int i=0;i<s.size();i++)
            Count[s[i]-'a']++;
            for(int i=0;i<s.size();i++)
            if(Count[s[i]-'a']==1)return i;
            return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_69061857/article/details/130091892
今日推荐