字符串排序可能不同但内容是相同的输出True帮我写出这道算法题目的JAVA代码
时间: 2024-05-24 11:12:45 浏览: 15
public static boolean isPermutation(String s1, String s2) {
if(s1.length() != s2.length()) {
return false;
}
char[] chars1 = s1.toCharArray();
char[] chars2 = s2.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
return Arrays.equals(chars1, chars2);
}
相关问题
字符串排序可能不同但内容是相同的输出True帮我写出这道算法题目的完整JAVA代码
public class StringSort {
public static boolean isSame(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}
public static void main(String[] args) {
String str1 = "hello";
String str2 = "lleho";
boolean result = isSame(str1, str2);
System.out.println(result);
}
}
请你写出一个算法判断字符串s里的所有字母字符是否全都不同,相同输出1,不相同输出0
可以使用哈希表来对字符串进行处理,遍历字符串s的每一个字符,如果该字符在哈希表中已存在,则表示字符串里有重复的字符,输出0;否则将该字符插入哈希表中。
具体实现可以参考以下代码:
```
def is_all_uniq_chars(s):
# 使用哈希表记录所有出现过的字符
char_dict = {}
for c in s:
if c in char_dict:
return 0
else:
char_dict[c] = True
return 1
```
注意,这个算法的时间复杂度是O(n),其中n为字符串s的长度。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)