头图

title: Daily Practice (23): The first character that appears only once

categories:[Swords offer]

tags:[Daily practice]

date: 2022/02/22


Daily practice (23): The first character that appears only once

Find the first character that occurs only once in the string s. If not, return a single space. s contains only lowercase letters.

Example 1:

Input: s = "abaccdeff"

output: 'b'

Example 2:

Input: s = ""

output: ' '

limit:

0 <= length of s <= 50000

Source: LeetCode

Link: https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof

Method 1: Hash table

ideas

1. Iterate over the string twice.

  • Traverse the string s and use the hash table to count "whether the number of characters is >1".
  • Then traverse the string s , find the first "character with a quantity of 1" in the hash table, and return.

algorithm

1. Character statistics: Traverse each character c in the string s;

  • If the key (key) c is not included in dic: add a key-value pair (c, True) to dic, representing the number of characters c is 1;
  • If the key (key) c is included in dic: then the key-value pair of the modified key c is (c, False), representing the number of characters c>1.

2. Find characters with a number of 1: Traverse each character c in the string s;

  • If the value corresponding to the key c in dic is True:, return c.

3. Returns ' ', which means that the string has no character whose number is 1.

char firstUniqChar(string s) {
    if (s.empty()) {     //注意边界情况的处理!特别是s为空字符串的情况
        return ' ';
    }
    unordered_map<int, bool> dic;
    for (char c : s) {
        dic[c] = dic.find(c) == dic.end();
    }
    for (char c : s) {
        if (dic[c]) {
            return c;
        }
    }
    return ' ';
}

Method 2: Use the search function of the string container skillfully

Ideas and Algorithms

  • s.find(s[i]) : Returns the position in the string s to find the first occurrence of s[i] from left to right;
  • s.rfind(s[i]) : Returns the position in the string s to find the first occurrence of s[i] from right to left;

Although this method looks simple in code, the time complexity of is !

char firstUniqChar(string s) {
    if (s.empty()) {    //注意边界情况的处理!特别是s为空字符串的情况
        return ' ';
    }
    int n = s.size();
    for(int i = 0; i < n; i++){
        if(s.find(s[i]) == s.rfind(s[i])){
            return s[i];
        }
    }
    return ' ';
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记