删除字符串和数组中重复的字符

删除重复的字符串

方法一(该方法只能判断连续的字符串)

public class Delzi {
         public static void main(String[] args) {
    String str="aabbbccdddddeee";
    String result=removeRepeatChar(str);
    System.out.println(result);
}
public static String removeRepeatChar(String s) {
    if (s == null) {
        return "";
    }
    StringBuffer sb = new StringBuffer();
    int i = 0;
    int len = s.length();
    while (i < len) {
        char c = s.charAt(i);
        sb.append(c);
        i++;
        while (i < len && s.charAt(i) == c) {//这个是如果这两个值相等,就让i+1取下一个元素
            i++;
        }
    }
    return sb.toString();
}
}

方法二

import java.util.ArrayList;
import java.util.List;

public class delchongfu {
      public static void main(String[] args) {
            String str = "asdadasfsasa";
    
            List<String> data = new ArrayList<String>();
    
            for (int i = 0; i < str.length(); i++) {
                String s = str.substring(i, i + 1);
                if (!data.contains(s)) {
                    data.add(s);
                }
            }
    
            String result = "";
            for (String s : data) {
                result += s;
            }
            System.out.println(result);
        }
}

方法三 (HashSet法)

package zifuchuan;

import java.util.HashSet;

public class HashSetTest {
    
    public static HashSet<Character> hashsetTest(String aa) {
    
    HashSet<Character> newhash = new HashSet<>();
    int i = 0;
    
    while(i<aa.length()) {
        
    char c = aa.charAt(i);
    newhash.add(c);
    i++;
        }
    return newhash;
    }
    
    public static void main(String[] args) {
        String str = "aabbccaabbcc";
        HashSet<Character> newhash = hashsetTest(str);
        for(char cc : newhash) {
            System.out.print(cc);
        }
        
    }

对于数组同理

public static void main(String[] args) {

int []a = {1,2,122,3,1,5,9,8,5,6};
HashSet set = new HashSet();
for (int i = 0 ; i < a.length; i++){
set.add(a[i]);
}
Iterator item = set.iterator();
         while(item.hasNext()){
        System.out.println(item.next());
     }
}

猜你喜欢

转载自blog.csdn.net/qq_29373285/article/details/84940771
今日推荐