Leetcode题解:First Unique Character in a String
2016-09-06 01:17
381 查看
题目:Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
难度:Easy
解题思路:比较容易想到的方法是用哈希表,先遍历一遍字符串,因为只有26个小写字母,开一个大小为26的数组a,对每一个扫到的字母,a[s[i]-'a']++,这样可以记录每个字母出现的次数,再遍历一遍字符串,找出a[s[i]-'a']=1的下标i,这种做法时间复杂度为O(n)
class Solution {
public:
int firstUniqChar(string s) {
int stre=s.size();
int a[26]={0};
int ans=-1;
for(int i = 0;i<s.size(); i++)
{
int x=s[i]-'a';
a[x]++;
}
for(int i = 0; i<s.size() ;i++)
{
if(a[s[i]-'a']==1)
{
ans=i;
break;
}
}
return ans;
}
};
难度:Easy
解题思路:比较容易想到的方法是用哈希表,先遍历一遍字符串,因为只有26个小写字母,开一个大小为26的数组a,对每一个扫到的字母,a[s[i]-'a']++,这样可以记录每个字母出现的次数,再遍历一遍字符串,找出a[s[i]-'a']=1的下标i,这种做法时间复杂度为O(n)
class Solution {
public:
int firstUniqChar(string s) {
int stre=s.size();
int a[26]={0};
int ans=-1;
for(int i = 0;i<s.size(); i++)
{
int x=s[i]-'a';
a[x]++;
}
for(int i = 0; i<s.size() ;i++)
{
if(a[s[i]-'a']==1)
{
ans=i;
break;
}
}
return ans;
}
};
相关文章推荐
- Gradle中的buildScript代码块
- UVA424 - Integer Inquiry
- 获取树选中叶子节点以及所有关联父节点(easyui tree)
- 2D UI和3D UI的工作原理
- POI操作Excel时出现Cannot get a text value from a numeric cell的异常错误
- 多线程(加载图片)一NSOperation & NSOperationQueue
- WinForms界面控件初探:功能完善的PDF浏览控件PDF Viewer Control
- easyui的简单使用
- druid 配置登录
- 在 iOS 中使用 HTML 模版和 UIPrintPageRenderer 生成 PDF
- Codeforces Round #349 (Div. 2) C. Reberland Linguistics (DP)
- 可任意自定义的 UITableViewCell
- mac下使用Elecard Video QuEst比较视频质量
- 【leetcode】347. Top K Frequent Elements
- UEFI与MBR区别
- @RequestParam @RequestBody @PathVariable 等参数绑定注解详解(转)
- GUI图形界面续
- 使用request对象获取表单的信息
- Leetcode 392. Is Subsequence 判断子序列 解题报告
- 十三、java_GUI