首先要向C(C++)致敬,这是我接触到的第一门计算机编程语言,本文参考了剑指offer—求字符串中第一个只出现一次的字符的范例,突发奇想用java实现,虽然相对于C(C++),Java在效率上较为低下了许多,但是思想还是可以为大家所参考的,下面直接上代码:
package commonTest;
import java.util.HashMap;
import java.util.Map;
public class FirstOnceCharTest
{
public static void main(String[] args)
{
// FirstOnceCharTest firstOnceCharTest = new FirstOnceCharTest();
FirstOnceChar firstOnceChar = new FirstOnceCharTest().new FirstOnceChar();
String string = "dskjcndskjgoiesfjsdvbdfkjsnvfdjkvrfdvnfdslsdjfefsdvn";
System.out.println(firstOnceChar.firstOnceChar(string));
}
class FirstOnceChar{
public char firstOnceChar(String str)
{
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++)
{
str.charAt(i);
if(map.get(str.charAt(i)) == null)
{
map.put(str.charAt(i), 1);
}
else
{
map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
}
}
char temp = 0;
for (Character character: map.keySet())
{
if(map.get(character) == 1)
{
temp = character;
break;
}
}
return temp;
}
}
}
上述代码运行结果如下:
g
作者声明:有问题请联系
[email protected]