Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit b6a3322

Browse files
committed
Unique char in string: done
1 parent 50de257 commit b6a3322

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

src/main/java/com/leetcode/strings/AnagramsInString.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,10 @@ private static List<Integer> findAllAnagramsInTextNaive(String text, String patt
5050
}
5151

5252
/**
53-
* Time complexity: O(n). Completes within <a href="https://leetcode.com/submissions/detail/222911434/">7ms on
54-
* leetcode.</a>
53+
* Completes within <a href="https://leetcode.com/submissions/detail/222911434/">7ms on leetcode.</a>
54+
* Time complexity: O(n)
55+
* where,
56+
* n = length of text or number of characters in text
5557
*
5658
* @param text
5759
* @param pattern
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.leetcode.strings;
2+
3+
/**
4+
* Leetcode Problem: https://leetcode.com/problems/first-unique-character-in-a-string/
5+
*
6+
* @author rampatra
7+
* @since 2019-04-16
8+
*/
9+
public class UniqueCharacterInString {
10+
11+
/**
12+
* Completes within <a href="https://leetcode.com/submissions/detail/222914261/">7ms on leetcode.</a>
13+
* Time complexity: O(n)
14+
*
15+
* @param str the input string
16+
* @return the index of the first non-repeating character in {@code str}, {@code -1} otherwise.
17+
*/
18+
private static int findFirstUniqueCharacterInString(String str) {
19+
int[] charCount = new int[26];
20+
21+
for (int i = 0; i < str.length(); i++) {
22+
charCount[str.charAt(i) - 'a']++;
23+
}
24+
25+
for (int i = 0; i < str.length(); i++) {
26+
if (charCount[str.charAt(i) - 'a'] == 1) {
27+
return i;
28+
}
29+
}
30+
return -1;
31+
}
32+
33+
public static void main(String[] args) {
34+
System.out.println(findFirstUniqueCharacterInString("leetcode"));
35+
System.out.println(findFirstUniqueCharacterInString("loveleetcode"));
36+
}
37+
}

0 commit comments

Comments
 (0)