HR자바 Java Substring Comparisons

개요[ | ]

HR자바 Java Substring Comparisons
해커랭크 Java
# 문제 비고
HR자바 Strings e
14 HR자바 Java Strings Introduction
15 HR자바 Java Substring
16 HR자바 Java Substring Comparisons
17 HR자바 Java String Reverse
18 HR자바 Java Anagrams
19 HR자바 Java String Tokens
20 HR자바 Pattern Syntax Checker
21 HR자바 Java Regex
22 HR자바 Java Regex 2 - Duplicate Words
23 HR자바 Valid Username Regular Expression
24 HR자바 Tag Content Extractor

Java
Copy
import java.util.Scanner;

public class Solution {
Java
Copy
    public static String getSmallestAndLargest(String s, int k) {
        String smallest = s.substring(0,k);
        String largest = s.substring(0,k);
        
        // Complete the function
        // 'smallest' must be the lexicographically smallest substring of length 'k'
        // 'largest' must be the lexicographically largest substring of length 'k'
        String ss;
        for(int i=1; i<s.length()-k+1; i++) {
            ss = s.substring(i,i+k);
            if( ss.compareTo(smallest)<0 ) smallest=ss;
            if( ss.compareTo(largest)>0 ) largest=ss;
        }
        return smallest + "\n" + largest;
    }
Java
Copy
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        int k = scan.nextInt();
        scan.close();
      
        System.out.println(getSmallestAndLargest(s, k));
    }
}