当前位置: 首页 > news >正文

LeetCode //C - 387. First Unique Character in a String

387. First Unique Character in a String

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
 

Example 1:

Input: s = “leetcode”
Output: 0
Explanation:
The character ‘l’ at index 0 is the first character that does not occur at any other index.

Example 2:

Input: s = “loveleetcode”
Output: 2

Example 3:

Input: s = “aabb”
Output: -1

Constraints:
  • 1 < = s . l e n g t h < = 1 0 5 1 <= s.length <= 10^5 1<=s.length<=105
  • s consists of only lowercase English letters.

From: LeetCode
Link: 387. First Unique Character in a String


Solution:

Ideas:

1. Frequency Array: We use an array freq[26] to store the count of each character. Since there are only 26 lowercase English letters, we can map each character to an index (s[i] - ‘a’).

2. First Pass: We iterate through the string once and count how many times each character appears.

3. Second Pass: We iterate through the string again and check the frequency of each character. The first character with a frequency of 1 is the first unique character, and we return its index.

4. Edge Case: If no unique character is found, the function returns -1.

Code:
int firstUniqChar(char* s) {int freq[26] = {0};  // Array to store frequency of each character// First pass: count the frequency of each characterfor (int i = 0; s[i] != '\0'; i++) {freq[s[i] - 'a']++;}// Second pass: find the first character with frequency 1for (int i = 0; s[i] != '\0'; i++) {if (freq[s[i] - 'a'] == 1) {return i;  // Return the index of the first unique character}}return -1;  // If no unique character is found, return -1
}

http://www.mrgr.cn/news/37277.html

相关文章:

  • Spring Boot 进阶- Spring Boot日志框架介绍
  • ArcGIS与ArcGIS Pro去除在线地图服务名单
  • C++:笔试题
  • 深入理解C#中的装箱与拆箱操作及其性能影响
  • 力扣经典笔试题 最小K个数 小根堆 大根堆 快速排序 一题多解
  • 硬件设计很简单?合宙低功耗4G模组Air780E—开机启动及外围电路设计
  • 代码随想录算法训练营第四四天| 1143.最长公共子序列 1035.不相交的线 53. 最大子序和 392.判断子序列
  • 大学生科技竞赛系统小程序的设计
  • Day 2 词汇备战
  • MySQL_插入、更新和删除数据
  • 【Python报错已解决】TypeError: list indices must be integers or slices, not str
  • [网络]数据链路层-MAC帧与ARP协议
  • java日志门面之JCL和SLF4J
  • ICM20948 DMP代码详解(46)
  • 个人文章汇总(MyBatis)
  • 解决 Adobe 盗版弹窗
  • Linux在桌面和服务器领域的最新技术趋势,包括3D桌面、虚拟技术、安全性提升等维度。
  • 11 函数的定义和使用
  • FastAPI 第五课 -- 基本路由
  • 显示技术概念极简理解(分辨率、英寸、PPI、DPI)