Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class _4_LongestAlphabeticalWord {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- String word = scan.next();
- int size = scan.nextInt();
- String longestWord = "" + word.charAt(0);
- if (word.length() > 1 && size > 1) {
- char[][] matrix = createMatrixOfWordLetters(word, size);
- ArrayList<String> wordsList = new ArrayList<String>();
- for (int row = 0; row < matrix[0].length; row++) {
- for (int col = 0; col < matrix[1].length; col++) {
- String rightWord = findNextAlpabeticalWord(matrix, row,
- col, 0, 1);
- wordsList.add(rightWord);
- String downWord = findNextAlpabeticalWord(matrix, row, col,
- 1, 0);
- wordsList.add(downWord);
- String leftWord = findNextAlpabeticalWord(matrix, row, col,
- 0, -1);
- wordsList.add(leftWord);
- String upperWord = findNextAlpabeticalWord(matrix, row,
- col, -1, 0);
- wordsList.add(upperWord);
- }
- }
- longestWord = findTheLongestAlphabeticalWordInArrayList(wordsList);
- }
- System.out.println(longestWord);
- }
- private static char[][] createMatrixOfWordLetters(String text, int length) {
- char[][] matrix = new char[length][length];
- int index = 0;
- for (int row = 0; row < matrix[0].length; row++) {
- for (int col = 0; col < matrix[1].length; col++) {
- matrix[row][col] = text.charAt(index % text.length());
- index++;
- }
- }
- return matrix;
- }
- private static String findNextAlpabeticalWord(char[][] matrix, int row,
- int col, int directY, int directX) {
- // TODO Auto-generated method stub
- int length = matrix[0].length;
- StringBuilder sb = new StringBuilder();
- char previous = matrix[row][col];
- sb.append(previous);
- while (true) {
- row += directY;
- col += directX;
- boolean isOutsideOfMatrix = row < 0 || row >= length || col < 0
- || col >= length;
- if (isOutsideOfMatrix || (matrix[row][col] <= previous)) {
- break;
- }
- sb.append(matrix[row][col]);
- previous = matrix[row][col];
- }
- return sb.toString();
- }
- private static String findTheLongestAlphabeticalWordInArrayList(
- ArrayList<String> wordsList) {
- wordsList.sort(null);
- String maxLettersStr = "";
- int maxCountLetters = 0;
- for (String wordStr : wordsList) {
- if (wordStr.length() > maxCountLetters) {
- maxCountLetters = wordStr.length();
- maxLettersStr = wordStr;
- }
- }
- return maxLettersStr;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement