practice question part 1
practice question part 2
这是一个练习题,对我来说相当难。下面是我的静态方法代码(主要方法是固定的-unchangeable,并给出了静态方法的签名),我的目的是获取字符之间的匹配并将其打印出来。
但也有一些担忧:
1)当所有字符串都对齐了,但是有额外的字符使得布尔值为false,并且结果不对齐时,我如何确保它不打印?(例如amgk作为第二个字符串,第一个字符串是Java编程课程)
2)如何正确打印?目前,空格是关闭的,字母不是我们想要的。
3)如果str1中有多个字符a,我应该选择放入哪个字符,如果已经存在匹配,如何省略其余字符?
我真的很欣赏伪代码来帮助像我这样的初学者解决这个问题。
public class Q3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first string:");
String input1 = sc.nextLine();
System.out.print("Enter the second string:");
String input2 = sc.nextLine();
System.out.println();
if (matchStrings(input1, input2)) {
System.out.println();
System.out.println("There is an alignment as shown above.");
} else {
System.out.println("No alignment can be found.");
}
}
public static boolean matchStrings(String str1, String str2) {
// Modify the code below to return the correct value.
boolean isMatch = false;
//int firstChar = str2.charAt(0);
//int lastChar = str2.charAt(str2.length()-1);
int prevIndex = 0;
System.out.println(str1);
for (int j = 0; j< str2.length(); j++) {
for (int i = 0; i<str1.length();i++) {
char charToSearch = str1.charAt(i);
int newIndex = i;
if (str2.charAt(j)== charToSearch) {
for (int k = prevIndex; k < newIndex-1; k++) {
System.out.print(" ");
}
System.out.print(charToSearch);
//prevIndex=newIndex+1;
isMatch = true;
}
}
}
return isMatch;
}
}发布于 2016-09-23 01:53:29
我认为你在数据结构课程中学到的前几个结构中有两个是栈和队列。因此,我将提供一个使用Stack的实现。您可以使用堆栈来存储测试字符串,并在每个字符元素与第一个字符串中的字符匹配时将其pop出堆栈。否则,您将在matched String对象中输出一个空格" ":
Stack s2 = new Stack();
String str1 = "Java Programming";
String str2 = "amg";
for(int i = str2.length()-1; i >= 0; i--){ //Need to populate the stack backwards...LIFO
s2.push(str2.charAt(i));
}
String match = ""; //Used to store the matching line
for(int i = 0; i < str1.length(); i++){
if(str1.charAt(i) == (char)s2.peek()){
match += s2.pop().toString();
}
else
{
match += " ";
}
}
System.out.println(str1);
System.out.println(match);您也可以使用队列来实现这一点,但我将留给您自己去学习。还要练习使用数组和整数指针创建自己的Stack对象来处理溢出/下溢。
上面的代码将打印出来:

https://stackoverflow.com/questions/39641845
复制相似问题