Given an input string, Write a PHP code to find the first Non-repeated character in a string. Suppose an input string is webrewrite, the first non-repeated character in this string is b.
How to Find First Non-Repeating Character in a String
Method 1 – Naive Approach
Use two for loops and compare each character with every character of a string. But the time complexity of this approach is O(n2).
Method 2 – Create a key and value pairs for character and it’s count
We can create a key and value pairs for character and it’s count. This approach is much better as compared to first one. Let’s implement this method.
PHP Code to Find the First Non-Repeated Character in a String
Let’s try to solve this problem in a single traversal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
/* Input string */ $str = "studentduniya"; /* Create an array of characters */ $str = str_split($str); $arr = array(); /* Traverse the string and make a key and value pairs. key represent character value represent it's count. */ foreach($str as $val){ $arr[$val] +=1; } /* If we print_r($arr), it will print Array ( [s] => 1 [t] => 2 [u] => 2 [d] => 2 [e] => 1 [n] => 2 [i] => 1 [y] => 1 [a] => 1 ) */ /* Traverse the array and check for character with a value 1 */ foreach($arr as $key => $value){ if($value == 1){ echo "First non-repeated character is $key"; break; } } /* Output : First non-repeated character is s */ |
Method 2:
Java Program to find the first non-repeated character in a string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* Input string */ $str = "studentduniya"; /* Convert a string into an array. */ $str = str_split($str); /* Count all the values of an array. */ $arr = array_count_values($str); foreach($arr as $key => $value){ if($value == 1){ echo "First non-repeated character is $key"; break; } } |
Conclusion
If you know some other efficient way to solve this problem then let us know through your comments.