题目描述

在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出'b'。

牛客网刷题地址

思路分析

可以遍历一遍字符串,将其存在map里面,并统计出现的次数,返回出现次数为1时的位置

测试用例

  1. 功能测试:字符串中存在只出现一次的字符;字符串中不存在只出现一次的字符;字符串中所有字符都只出现一次。
  2. 特殊输入测试:字符串为nullptr指针。

Java代码

public class Offer050_01 {
public static void main(String[] args) {
test1();
test2();
test3(); } public static int FirstNotRepeatingChar(String str) {
return Solution1(str);
} private static int Solution1(String str) {
if (str.length() == 0 || str == null) {
return -1;
}
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (hashMap.containsKey(c)) {
hashMap.put(c, hashMap.get(c) + 1);
} else {
hashMap.put(c, 1);
}
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (hashMap.get(c) == 1) {
return i;
}
}
return 0;
} public int Solution2(String str) {
if (str == null || str.length() == 0)
return -1;
int[] repetitions = new int[256];
for (int i = 0; i < 256; i++)
repetitions[i] = 0;
for (int i = 0; i < str.length(); i++) {
int loc = (int) str.charAt(i);
repetitions[loc] += 1;
}
for (int i = 0; i < str.length(); i++) {
int loc = (int) str.charAt(i);
if (repetitions[loc] == 1)
return i;
}
return -1;
} private static void test1() {
}
private static void test2() {
}
private static void test3() {
}
}

代码链接

剑指Offer代码-Java

最新文章

  1. Start with connect by prior 递归查询
  2. mysql 字符串
  3. css hack整理:区别FF,IE8,IE7,IE6,SF,CH浏览器
  4. 【linux】grub详解
  5. springMVC从上传的Excel文件中读取数据
  6. (转)[老老实实学WCF] 第二篇 配置WCF
  7. Java NIO与IO
  8. Java并发之线程异常捕获
  9. JavaScript面向对象中的继承
  10. java单例设计模式总结及举例
  11. html 知识整理
  12. 自定义标签在IE6-8的困境
  13. C语言 &#183; 确定元音字母位置
  14. mysql主服务器 binlog_format 的 statement,row, mixed 三种格式对比。
  15. SpringBoot整合MyBatis及Thymeleaf
  16. 学习Android开发看那些书好?
  17. LeetCode 刷题指南(1):为什么要刷题
  18. MemoryCache缓存 ---缓存时效
  19. &quot;todoList妙味&quot;学习总结
  20. 删除 char[10][10] 中的一行

热门文章

  1. 客户端埋点实时OLAP指标计算方案
  2. 对比度拉伸(一些基本的灰度变换函数)基本原理及Python实现
  3. leetcode 29 两数相除
  4. hadoop安装解决之道
  5. S3 Select for Java 使用记录
  6. mysql复制那点事(2)-binlog组提交源码分析和实现
  7. 使用idea在linux上启动springboot项目
  8. JVM类生命周期概述:加载时机与加载过程
  9. Console也要美颜了,来给Console添色彩
  10. spark sql/hive小文件问题