java 字符串重复函数_java – 函数删除字符串中的重复字符

这个功能对我看起来不错。我写了内嵌注释。希望它有帮助:

// function takes a char array as input.

// modifies it to remove duplicates and adds a 0 to mark the end

// of the unique chars in the array.

public static void removeDuplicates(char[] str) {

if (str == null) return; // if the array does not exist..nothing to do return.

int len = str.length; // get the array length.

if (len < 2) return; // if its less than 2..can't have duplicates..return.

int tail = 1; // number of unique char in the array.

// start at 2nd char and go till the end of the array.

for (int i = 1; i < len; ++i) {

int j;

// for every char in outer loop check if that char is already seen.

// char in [0,tail) are all unique.

for (j = 0; j < tail; ++j) {

if (str[i] == str[j]) break; // break if we find duplicate.

}

// if j reachs tail..we did not break, which implies this char at pos i

// is not a duplicate. So we need to add it our "unique char list"

// we add it to the end, that is at pos tail.

if (j == tail) {

str[tail] = str[i]; // add

++tail; // increment tail...[0,tail) is still "unique char list"

}

}

str[tail] = 0; // add a 0 at the end to mark the end of the unique char.

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值