【业余练手系列】First Unique Character in a String

xiaoxiao2021-02-28  58

 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode" return 0. s = "loveleetcode", return 2.

Note: You may assume the string contain only lowercase letters.

实现方案: leetcode 调试通过,运行速度超越80%网友

104 / 104 test cases passed. Status:

Accepted

class Solution { public:     int firstUniqChar(string s)     {         if( s.empty() ) return -1;         int bExisted[256]={0};   //index as char         const  char *p=s.c_str();         int rthIdx=-1;         for (int i=0; i<s.size();i++)         {             int index=*(p+i)-'\0';             bExisted[index]++;                }       for (int i=0; i<s.size();i++)       {            int index=*(p+i)-'\0';             if ( 1== bExisted[index] )             {                 rthIdx =i;                 break;                }       }                 return rthIdx;     } };

转载请注明原文地址: https://www.6miu.com/read-55125.html

最新回复(0)