例如:
输入:
zyzyzyz
zyz
输出:
0
分析:String类有一个方法:contains(),该方法是判断字符串中是否有子字符串。如果有则返回true,如果没有则返回false。
code:
public static int findApperance(String A,int lenA,String B,int lenB){
if(!A.contains(B) || lenB>lenA){
return -1;
}else if (lenB==lenA) {
return 0;
}else {
return A.indexOf(B);
}
}
2)字符串B在字符串A中出现的次数
例如:
输入:
zyzyzyz
zyz
输出:
3
分析:substring() 方法返回字符串的子字符串。考虑用substring( i , j ) 截取子字符串,再用equals 方法进行字符串比较。
补充:substring() 时间复杂度 O(n),其中n是子串中的数字。
public String substring(int beginIndex)
或
public String substring(int beginIndex, int endIndex)
code:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.nextLine();
String B = sc.nextLine();
int num=numDistinct(A,B);
System.out.println(num);
sc.close();
}
public static int numDistinct(String A, String B) {
int lenB=B.length();
String strA;
//定义返回的次数
int count=0;
for (int i=0;i<A.length()&&i+lenB<=A.length();i++) {
strA=A.substring(i,i+lenB);
if (strA.equals(B))
count++;
}
return count;
}
}
3)删除字符串里面的重复字符
给定一个排序的字符串,删除字符串里面的重复字符,每个字符最多允许出现两次,返回
新的字符串和字符串的长度。
输入描述:
已排序字符串
字符串长度>0 && 字符串长度<100
输出描述:
字符串
整数
示例1
输入
12223333
输出
12233
5
分析,方法参考:leetcode 26. 删除排序数组中的重复项但是该方法可以计算长度,得不到新的正确的字符串。
补充: String ( char a[] , int offset , int length) 提取字符数组 a 中的一部分创建一个字符串对象。
参数 offset 表示开始截取字符串的位置 ,length 表示截取字符串的长度。
char a[]={‘s’ , ‘t’ , ‘u’ , ‘d’ , ‘e’ , ‘n’ , ‘t’ }; String s = new String (a , 2 , 4);
等价于 String s = new String(“uden”);
12223333 —》flag=0
12223333 —》flag=1
12223333 flag=2
12233333 flag=3
12233333 flag=4
12233333 flag=5
故新的字符串为:12233
代码:
public class test00 {
public static void main(String[] args) {
String str="1222333aabbccccccc";
String nStr;
nStr=removeDuplucate(str);
System.out.println("新的字符串为:"+nStr+ "新的字符串长度"+nStr.length());
}
public static String removeDuplucate(String str){
char[] chars=str.toCharArray();
int len=chars.length;
if(chars.length==0)//不能写char==null,因为char为索引,不会为空
return new String(chars);
int flag=0;//标志位判断
int count=0;//count 为出现的次数
for(int i=0;i<len;i++){
if(flag==0){//标志位为flag=0 时
chars[flag]=chars[i];
flag++;
}
/**
* 数组邻位元素不一致时
* 数组的flag 位赋值,count 记为1
* flag+1 往后遍历
*/
else if(chars[flag-1]!=chars[i]){//数组邻位元素不一致时
chars[flag]=chars[i];
flag++;//2
count=1;
}
/**
* 数组邻位元素一致时,判断重复出现的个数,最多两次
* 数组的flag 位赋值,count++
*/
else{
if(count<2){
chars[flag]=chars[i];
flag++;//3
count++;//2
}
}
}
return new String(chars,0,flag);
}
}