LeetCode-----First Unique Character in a String

我将于茫茫人海中访我唯一灵魂之伴侣;得之,我幸;不得,我命 。一徐志摩


要求:给定一个字符串,找到第一个不重复的字符,并返回它的索引。如果不存在,返回-1。


举例1:输入字符串 "leetcode",结果返回 0。

举例2:输入字符串 "loveleetcode",结果返回 2 。


思路:遍历整个字符串,定义一个变量用来记录该字符没有重复字符,当检验的字符与字符串中的其他字符进行比较时,如果不相等,变量自增。如果相等,变量归0,并跳出当前循坏。


时间复杂度O(n*n)

public class FirstUniqueCharacter {

	public static void main(String[] args) {
		String s1 = "z";
		String s2 = "ababababaaa";
		String s3 = "leetcode";
		String s4 = "loveleetcode";
		System.out.println("s1 FirstUniqueCharacter index is :"+firstUniqChar(s1));
		System.out.println("s2 FirstUniqueCharacter index is :"+firstUniqChar(s2));
		System.out.println("s3 FirstUniqueCharacter index is :"+firstUniqChar(s3));
		System.out.println("s4 FirstUniqueCharacter index is :"+firstUniqChar(s4));
	}

	public static int firstUniqChar(String s) {
		int index = -1;
		if (s.length() == 1) {
			return 0;
		}else if(s.length() >1){
			for (int i = 0; i < s.length(); i++) {
				char ch = s.charAt(i);
				for (int j = 0; j < s.length(); j++) {
					char temp = s.charAt(j);
					if(j != i) {
						if(ch != temp) {
							index++;
						}else {
							index = -1;
							break;
						}
					}else {
						continue;
					}
				}
				if (index >=0) {
					index = i;
					break;
				}
			}
			return index;
		}else {
			return -1;
		}
	}
}

结果显示:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值