-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_unique_chars.php
46 lines (39 loc) · 1 KB
/
string_unique_chars.php
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
<?php
// Author: Marguerite Desko
// Purpose: check if string has any repeating characters
function unique_chars($string) {
// get the length of the string
$length = strlen($string);
$character_count = array();
for ($i = 0; $i < $length; $i ++) {
$char = substr($string, $i, 1);
$character_count[$char] = $character_count[$char] + 1;
if ($character_count[$char] > 1) {
return FALSE;
}
}
return TRUE;
}
// do this using no other data structures
function unique_chars_noarray($string) {
// get the length of the string
$length = strlen($string);
// iterate through the string
for ($i = 0; $i < $length; $i++) {
$char = substr($string, $i, 1);
$remaining_string = substr($string, ($i+1));
if (strpos($remaining_string, $char) !== FALSE) {
return FALSE;
}
}
return TRUE;
}
$result = unique_chars_noarray($argv[1]);
if ($result === TRUE) {
echo 'The string '.$argv[1].' has only unique characters!';
}
else {
echo 'fail!';
echo 'The string '.$argv[1].' has non-unique characters!';
}
?>