[关闭]
@XQF 2018-03-07T22:59:25.000000Z 字数 1802 阅读 953

如何删除字符串中重复的字符?

数据结构与算法


应该是要保留原数组元素的相对位置
,。,。,。选择排序类似的筛选法没问题。

1.筛选

  1. public class Solution {
  2. public String removeDuplicate(String string) {
  3. if(string==null||string.length()==0){
  4. return null;
  5. }
  6. char[] chars = string.toCharArray();
  7. List<Character> charList = new ArrayList<>();
  8. for (int i = 0; i < chars.length; i++) {
  9. charList.add(chars[i]);
  10. }
  11. for (int i = 0; i < chars.length - 1; i++) {
  12. for (int j = i + 1; j < chars.length; j++) {
  13. if (chars[i] == chars[j]) {
  14. charList.remove(j);
  15. }
  16. }
  17. }
  18. return charList.toString();
  19. }
  20. public static void main(String[] args) {
  21. Solution solution = new Solution();
  22. String string = "abac";
  23. System.out.println(solution.removeDuplicate(string));
  24. }
  25. }

2.一次遍历

记录出现的字符

  1. public class Solution {
  2. public String removeDuplicate(String string) {
  3. if (string == null || string.length() == 0) {
  4. return null;
  5. }
  6. char[] chars = string.toCharArray();
  7. List<Character> charList = new ArrayList<>();
  8. for (int i = 0; i < chars.length; i++) {
  9. charList.add(chars[i]);
  10. }
  11. int len = 'z' - 'A' + 1;
  12. boolean[] book = new boolean[len];
  13. int temp;
  14. for (int i = 0; i < chars.length; i++) {
  15. temp = chars[i] - 'A';
  16. if (book[temp] == false) {
  17. book[temp] = true;
  18. } else {
  19. charList.remove(i);
  20. }
  21. }
  22. return charList.toString();
  23. }
  24. public static void main(String[] args) {
  25. Solution solution = new Solution();
  26. String string = "abac";
  27. System.out.println(solution.removeDuplicate(string));
  28. }
  29. }

3.不申请额外空间

,,。,就是直接置为'',.,.,.,

  1. public class Solution {
  2. public String removeDuplicate(String string) {
  3. if (string == null || string.length() == 0) {
  4. return null;
  5. }
  6. char[] chars = string.toCharArray();
  7. int len = 'z' - 'A' + 1;
  8. boolean[] book = new boolean[len];
  9. int temp;
  10. for (int i = 0; i < chars.length; i++) {
  11. temp = chars[i] - 'A';
  12. if (book[temp] == false) {
  13. book[temp] = true;
  14. } else {
  15. chars[i] = ' ';
  16. }
  17. }
  18. StringBuffer sb = new StringBuffer();
  19. for (int i = 0; i < chars.length; i++) {
  20. if (chars[i] != ' ') {
  21. sb.append(chars[i]);
  22. }
  23. }
  24. return sb.toString();
  25. }
  26. public static void main(String[] args) {
  27. Solution solution = new Solution();
  28. String string = "abac";
  29. System.out.println(solution.removeDuplicate(string));
  30. }
  31. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注