用java实现,查找字符串中第一个没有重复出现的字符

来源:互联网 发布:nginx servername作用 编辑:程序博客网 时间:2024/05/16 02:40

 

一道笔试题,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.  }  

 

原创粉丝点击