Guest User

Untitled

a guest
Apr 20th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. public static String removeDuplicate(String s) {
  2. StringBuilder builder = new StringBuilder();
  3. char lastchar = '';
  4. for (int i = 0; i < s.length(); i++) {
  5. String str = builder.toString();
  6. if (!str.equals("")
  7. && (str.charAt(str.length() - 1) == s.charAt(i))) {
  8. builder.deleteCharAt(str.length() - 1);
  9. } else if (s.charAt(i) != lastchar)
  10. builder.append(s.charAt(i));
  11. lastchar = s.charAt(i);
  12. }
  13. return builder.toString();
  14. }
  15.  
  16. public static String removeDuplicates(String s) {
  17. if (s.isEmpty()) {
  18. return s;
  19. }
  20. char[] buf = s.toCharArray();
  21. char lastchar = buf[0];
  22.  
  23. // i: index of input char
  24. // o: index of output char
  25. int o = 1;
  26. for (int i = 1; i < buf.length; i++) {
  27. if (o > 0 && buf[i] == buf[o - 1]) {
  28. lastchar = buf[o - 1];
  29. while (o > 0 && buf[o - 1] == lastchar) {
  30. o--;
  31. }
  32. } else if (buf[i] == lastchar) {
  33. // Don't copy to output
  34. } else {
  35. buf[o++] = buf[i];
  36. }
  37. }
  38. return new String(buf, 0, o);
  39. }
  40.  
  41. public class Test3 {
  42. public static void main(String[] args) {
  43. String str = "ABBCDAABBBBBBBBOR";
  44. char[] ca = str.toCharArray();
  45.  
  46. Arrays.sort(ca);
  47.  
  48. String a = new String(ca);
  49. System.out.println("original => " + a);
  50. int i = 0 ;
  51. StringBuffer sbr = new StringBuffer();
  52. while(i < a.length()) {
  53. if(sbr.length() == 0 ) {sbr.append(a.charAt(i));}
  54. if(a.charAt(i) == sbr.charAt(sbr.length() -1)) {i++ ;}
  55. else {sbr.append(a.charAt(i));}
  56. }//while
  57.  
  58. System.out.println("After removing the duplicates => " + sbr);
  59. }//main
  60. }// end1
Add Comment
Please, Sign In to add comment