一道筆試題,用java實現,查找字符串中第一個沒有重複出現的字符。譬如“teeter”就輸出“r” ,
如果是“teeterh”,還是輸出“r” 。
Java Codes:
1. public class TestCal{
2. public void Cal( String s ){
3. int n=0;
4. for(int i=0; i<s.length(); i++){
5. char t = s.charAt(i);
6. for(int j=0; j<s.length(); j++){
7. char tt = s.charAt(j);
8. if(t==tt)
9. n+=1;
10. }
11. if(n==1){
12. System.out.println("out result: "+t);
13. break;
14. }
15. n = 0;
16. }
17. }
18.
19. public static void main(String args[]) {
20. TestCal cal = new TestCal();
21. cal.Cal("teeter");
22. cal.Cal("teeterh");
23. cal.Cal("aaeeqerrabca");
24. cal.Cal("abc");
25. }
26. }
效率稍好的方法。
1. public static void main(String args[]) {
2. String inputStr = "teterhrecd";
3. HashMap hm = new HashMap();
4. char[] c = inputStr.toCharArray();
5. boolean isEcho;
6. //outside:
7. for (int i = 0; i < c.length; i++) {
8. if (hm.get(String.valueOf(c[i])) == null) {
9. isEcho=false;
10. //inside:
11. for (int j = i + 1; j < c.length; j++) {
12. if (c[i] == c[j]) {
13. isEcho=true;
14. hm.put(String.valueOf(c[i]), String.valueOf(c[i]));
15. break inside;
16. }
17. }
18. if(!isEcho){
19. System.out.println(c[i]);
20. break outside;
21. }
22. }
23. }
24. }
簡單的方法。
1. public class Simple{
2. public static char getChar(String text){
3. char c =0xff;
4. for(int index =0;index <text.length();index ++){
5. c =text.charAt(index);
6. if(text.indexOf(c) ==text.lastIndexOf(c)) break;
7. }
8. return c;
9. }
10.
11. public static void main(String[] args){
12. System.out.println(getChar("teeter"));
13. System.out.println(getChar("teeterh"));
14. }
15. }
用java實現,查找字符串中第一個沒有重複出現的字符
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.