Home>Article>Backend Development> PHP determines whether a string is repeated
PHP determines whether a string has repeated characters:
Method 1,
1. Convert the string into a character array
2. Use Arrays.sort(char[]) to sort the character array, and then traverse the entire sorted array one by one. If it is not the last character, and if the current character is the same as the character after it, then return false directly. , otherwise continue to traverse. If all elements are different from what follows or the last character has been traversed, it is considered that there are no repeated characters, that is, true
3 is returned. In addition, for null or the length is 0 The string has no repeated characters and returns true
Method 2,
Create a hash table and traverse the string. If the hash table does not contain the character, add it. If it does, , it returns false, if there are no repeated characters, then it finally returns true.
Method 3,
Both of the above two methods require additional space to be allocated. If you do not want to allocate space, you can use String.indexOf(char ch, int fromIndex) to traverse characters The characters in the string can be traversed to the penultimate character. For each character, just determine whether there are repeated characters thereafter. If so, return false. If there are no repeated characters, return true.
Implementation code:
public class Solution { /* * @param str: A string * @return: a boolean */ public boolean isUnique(String str) { // write your code here /* //思路一 //如果str是null,那么抛出异常 if(str == null){ throw new IllegalArgumentException("invalid parameters"); } //如果str的长度是0或者1,那么没有重复字符,返回true if(str.length() == 0 || str.length() == 1){ return true; } //将字符串转成字符数组 char[] ch = str.toCharArray(); //对数组进行排序 Arrays.sort(ch); //遍历数组,看当前字符是否和后面字符相同,相同就返回false,否则返回true for(int i = 0; i < ch.length-1; i++){ if(ch[i] == ch[i+1]){ return false; } } return true; */ /* //思路二 //如果str是null,那么抛出异常 if(str == null){ throw new IllegalArgumentException("invalid parameters"); } //如果str的长度是0或者1,那么没有重复字符,返回true if(str.length() == 0 || str.length() == 1){ return true; } //创建hash表,将字符串字符存到hash表中 HashSeths = new HashSet (); for(int i = 0; i < str.length(); i++){ if(hs.contains(str.charAt(i))){ return false;//hash表中有相同的字符,那么说明有重复的字符 } hs.add(str.charAt(i)); } return true; */ //思路三 //如果str是null,那么抛出异常 if(str == null){ throw new IllegalArgumentException("invalid parameters"); } //如果str的长度是0或者1,那么没有重复字符,返回true if(str.length() == 0 || str.length() == 1){ return true; } //从前向后遍历字符串,对每个字符,调用String.indexOf()看其后面是否有相同的字符,如果有返回false,否则最后返回true for(int i = 0; i < str.length()-1; i++){ if(str.indexOf(str.charAt(i), i+1) != -1){ return false; } } return true; } }
Recommendation:php server
The above is the detailed content of PHP determines whether a string is repeated. For more information, please follow other related articles on the PHP Chinese website!