Java 检查两个字符串是否包含相同顺序的相同字符
''给定两个字符串s和t,编写函数检查s是否包含t的所有字符(与字符串t中的字符顺序相同)。 返回真或假。 递归不是必需的。 下面是我用java编写的代码片段。 问题在于输入:string1=“st3h5irteuyarh!” 和string2=“shrey” 它应该返回TRUE,但返回FALSE。这是为什么Java 检查两个字符串是否包含相同顺序的相同字符,java,string,Java,String,''给定两个字符串s和t,编写函数检查s是否包含t的所有字符(与字符串t中的字符顺序相同)。 返回真或假。 递归不是必需的。 下面是我用java编写的代码片段。 问题在于输入:string1=“st3h5irteuyarh!” 和string2=“shrey” 它应该返回TRUE,但返回FALSE。这是为什么 公共类解决方案{ 公共静态字符串getString(char x) { 字符串s=字符串。值(x); 返回s; } 公共静态布尔校验序列(字符串s1、字符串s2) { 字符串a=ge
公共类解决方案{
公共静态字符串getString(char x)
{
字符串s=字符串。值(x);
返回s;
}
公共静态布尔校验序列(字符串s1、字符串s2)
{
字符串a=getString(s1.charAt(0));
字符串b=getString(s2.charAt(0));
对于(int i=1;i
这可能就是您正在搜索的内容
public class Solution {
public static boolean checkSequence(String s1, String s2) {
for(char c : s2.toCharArray()) {
if(!s1.contains(c+"")) {
return false;
}
int pos = s1.indexOf(c);
s1 = s1.substring(pos);
}
return true;
}
}
在代码中我可以看到两个问题 1
for(int i=1;i
您从索引1
开始,但字符串索引从0
2如果(s1.charAt(i)!=s1.charAt(i-1))
这里您是在其他循环中比较相同字符串的字符s1
,情况也是如此
请先修复这些问题,然后再次询问这是一个解决方案:
公共类解决方案{
公共静态字符串getString(char x)
{
字符串s=字符串。值(x);
返回s;
}
公共静态布尔校验序列(字符串s1、字符串s2)
{
字符串a=getString(s1.charAt(0));
字符串b=getString(s2.charAt(0));
整数计数=0;
对于(int i=0;i
- 在位置计数处,将字符串s1的每个字符与字符串s2的一个字符进行比较
- 如果匹配计数增加:
count++代码>
- 如果count的长度为字符串2,则返回所有匹配的字符和
true
- 您解决此问题的方法可以是这样的:
public static boolean checkSequence(String s1, String s2)
{
String smallerString = s1.length()<=s2.length() ? s1 : s2;
String largerString = smallerString.equals(s2) ? s1 : s2;
int smallerStringPointer=0;
for(int i=0;i<largerString.length();i++){
if(smallerString.charAt(smallerStringPointer) == largerString.charAt(i)){
smallerStringPointer++;
}
if(smallerStringPointer == smallerString.length()){
return true;
}
}
return false;
}
public static boolean checkSequence(String s1, String s2)
{
String smallerString = s1.length()<=s2.length() ? s1 : s2;
String largerString = smallerString.equals(s2) ? s1 : s2;
int smallerStringPointer=0;
for(int i=0;i<largerString.length();i++){
if(smallerString.charAt(smallerStringPointer) == largerString.charAt(i)){
smallerStringPointer++;
}
if(smallerStringPointer == smallerString.length()){
return true;
}
}
return false;
}
公共静态布尔校验序列(字符串s1、字符串s2)
{
字符串smallerString=s1.length()使用循环的公共静态布尔值(字符串str1,字符串str2){
int指数=-10;
int标志=0;
对于(int i=0;i
sorry递归不是必需的。请批准编辑。现在应该可以了
public static boolean usingLoops(String str1, String str2) {
int index = -10;
int flag = 0;
for (int i = 0; i < str1.length(); i++) {
flag = 0;
for (int j = i; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
if (j < index) {
return false;
}
index = j;
flag = 1;
break;
}
}
if (flag == 0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str1 = s.nextLine();
String str2 = s.nextLine();
// using loop to solve the problem
System.out.println(usingLoops(str1, str2));
s.close();
}