字符串篇(leetcode—最长公共前缀)
发布时间 2023-12-20 17:49:18作者: 吧拉吧拉吧
字符串
- 百度百科:字符串或串(String)是由数字、字母、下划线组成的一串字符。一般记为 s="a1a2···an"(n>=0)。它是编程语言中表示文本的数据类型。
- 常用函数
- 比较函数
- C++、Python等支持运算符重载的语言——可以使用 == 来比较两个字符串
- JAVA等不支持运算符重载——可能无法使用 == 来比较两个字符串。当我们使用 == 时,它实际上会比较这两个对象是否是同一个对象。可以使用compareTo() 或者 equals()
- compareTo函数比较两个字符串,并返回一个int类型。若字符串等于参数字符串,则返回0,字符串小于参数字符串,则返回值小于0;字符串大于参数字符串,返回值大于0。
- equals比较内容是否相等,返回true或false
String str1="abcd";
String str2="abce";
if(str1==str2){
System.out.print("yes");
}else{
System.out.print("no");
}
// 结果输出yes
String str3=new String("abcd");
if(str1==str3){
System.out.print("yes");
}else{
System.out.print("no");
}
// 结果输出no,str1和str3指向不同的对象
//使用equal比较
if(str1.equal(str3)){
System.out.print("yes");
}else{
System.out.print("no");
}
// 结果输出yes
//使用compareTo比较
if(str1.compareTo(str3)==0){
System.out.print("yes");
}else{
System.out.print("no");
}
// 结果输出yes
- 获取字符串长度
- 连接函数
- 其他常见JAVA String类的方法
- indexOf() 方法
- public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- substring() 方法
- 分析:
- 这个函数首先检查输入的字符串数组是否为空或长度为0,如果是,则返回空字符串。
- 然后,它将第一个字符串作为初始前缀。
- 然后,循环数组中的每个其他字符串,如果不以该前缀prefix开始,那么前缀就会被减少一个字符,直到找到一个前缀,所有的字符串都以它开始,或者前缀变为空字符串。如果前缀变为空字符串,那么函数返回空字符串。否则,函数返回找到的最长前缀。
- 代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
}