本文主要是介绍《Java语言程序设计与数据结构》编程练习答案(第二十二章)(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《Java语言程序设计与数据结构》编程练习答案(第二十二章)(一)
英文名:Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Edition
22.1
public class book {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a string:");String xxx = input.nextLine();int start = 0;int end = 1;if (xxx.length() != 1) {int head = 0;int tail = 1;int maxLength = 1;while (tail < xxx.length()) {while(tail < xxx.length() && xxx.charAt(tail-1) < xxx.charAt(tail)){tail++;}if(tail - head > maxLength){maxLength = tail - head;start = head;end = tail;head = tail;tail++;}}for(int i=start;i<end;i++){System.out.print(xxx.charAt(i));}}else{System.out.println(xxx);}}
}
22.2
public class book {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a string:");String xxx = input.nextLine();int[] max = new int[xxx.length()];String[] lcs = new String[xxx.length()];for(int i = 0;i < xxx.length();i++){max[i] = 1;lcs[i] = xxx.charAt(i)+"";}for(int i = 1;i < xxx.length();i++){for(int j=0;j<i;j++){if(xxx.charAt(i) > xxx.charAt(j) && max[i] < max[j]+1){max[i] = max[j] + 1;lcs[i] = lcs[j] + xxx.charAt(i);}}}int maxLen = 0;int maxIndex = 0;for(int i=0;i<xxx.length();i++){if(maxLen < max[i]){maxLen = max[i];maxIndex = i;}}System.out.println(lcs[maxIndex]);}
}
22.3
KMP
22.4
public class book {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a string s1:");String s1 = input.nextLine();System.out.println("Enter a string s2:");String s2 = input.nextLine();int index = -1;for(int i=0;i <= s1.length()-s2.length();i++){boolean success = true;for(int j=0;j<s2.length();j++){if(s1.charAt(i+j)!=s2.charAt(j)){success = false;break;}}if(success){index = i;}}if(index != -1){System.out.println("Matched at index "+index);}else{System.out.println("Not match");}}
}
22.5
public class book {public static void main(String[] args) {Scanner input = new Scanner(System.in);ArrayList<Integer> numbers = new ArrayList<>();System.out.println("Please enter a sequence ending with 0:");while(true){int tmp = input.nextInt();if(tmp == 0){break;}else{numbers.add(tmp);}}int maxLen = 0;int maxIndex = 0;int head = 0;while (head < numbers.size()-1){int tmpIndex = head;int len = 1;while(head < numbers.size()-1 && numbers.get(head).equals(numbers.get(head + 1))){len++;head++;}if(len > maxLen){maxLen = len;maxIndex = tmpIndex;}head++;}System.out.println("The longest same number sequence starts at index "+maxIndex+" with "+maxLen+" values of "+numbers.get(maxIndex));}
}
22.6
我爬了
这篇关于《Java语言程序设计与数据结构》编程练习答案(第二十二章)(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!