【Offer】[50-1] 【第一个只出现一次的字符】
2024-09-01 07:09:54
题目描述
在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出'b'。
思路分析
可以遍历一遍字符串,将其存在map里面,并统计出现的次数,返回出现次数为1时的位置
测试用例
- 功能测试:字符串中存在只出现一次的字符;字符串中不存在只出现一次的字符;字符串中所有字符都只出现一次。
- 特殊输入测试:字符串为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() {
}
}
代码链接
最新文章
- Start with connect by prior 递归查询
- mysql 字符串
- css hack整理:区别FF,IE8,IE7,IE6,SF,CH浏览器
- 【linux】grub详解
- springMVC从上传的Excel文件中读取数据
- (转)[老老实实学WCF] 第二篇 配置WCF
- Java NIO与IO
- Java并发之线程异常捕获
- JavaScript面向对象中的继承
- java单例设计模式总结及举例
- html 知识整理
- 自定义标签在IE6-8的困境
- C语言 &#183; 确定元音字母位置
- mysql主服务器 binlog_format 的 statement,row, mixed 三种格式对比。
- SpringBoot整合MyBatis及Thymeleaf
- 学习Android开发看那些书好?
- LeetCode 刷题指南(1):为什么要刷题
- MemoryCache缓存 ---缓存时效
- ";todoList妙味";学习总结
- 删除 char[10][10] 中的一行