2、findFirstOneTimeChar

题目

请实现一个函数,输入一个字符串,找出第一个只出现一次的字符。

输入

“asdfasdfo”

输出

‘o’

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static char findFirstOneTimeChar(String input) {
if (input == null || input.length() <= 0) {
return 0;
}
char[] chars = input.toCharArray();
final int[] numArray = new int[256];
for (char curChar : chars) {
numArray[curChar]++;
}
for (char curChar : chars) {
if (numArray[curChar] == 1) {
return curChar;
}
}
return 0;
}

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class FindFirstOneTimeCharTest {

@Test
public void testNulInput() {
Assert.assertEquals(FindFirstOneTimeChar.findFirstOneTimeChar(null), 0);
}

@Test
public void testEmptyInput() {
Assert.assertEquals(FindFirstOneTimeChar.findFirstOneTimeChar(""), 0);
}

@Test
public void testSpaceInput() {
Assert.assertEquals(FindFirstOneTimeChar.findFirstOneTimeChar(" "), ' ');
}

@Test
public void testNormalInput() {
String input = "asdfasdfo";
char expect = 'o';
char result = FindFirstOneTimeChar.findFirstOneTimeChar(input);
Assert.assertEquals(expect, result);
}
}