如何按字典顺序排序子字符串

时间:2019-04-13 10:25:32

标签: java string compareto

我想按字母顺序对长度为'k'的字符串's'的子字符串进行排序

我尝试首先使用comapareTo函数按字母顺序对字符串的字符进行排序,然后尝试打印第一个和最后一个子字符串

public static String getSmallestAndLargest(String s, int k) {
    String smallest = "";
    String largest = "";
    char ch1,ch2,temp;
    int i,j,res; 

    // 'smallest' must be the lexicographically smallest substring of length 'k'
    // 'largest' must be the lexicographically largest substring of length 'k'
    for(i=0;i<s.length();i++)
    {
        ch1=s.charAt(i);
        for(j=i+1;j<=s.length();j++)
        {
            ch2=s.charAt(j);
            res=ch2.compareTo(ch1);
            if(res<0)
            {
                temp=ch2;
                ch2=ch1;
                ch1=temp;
            }
        }
    }
    smallest=s.substring(0,k);
    largest=s.substring(s.length()-k);
    return smallest + "\n" + largest;
}

预期的输出:将按字典顺序的最小和最大子字符串作为单个换行符分隔的字符串返回。

input: welcometojava
3

expected output:ava
wel

2 个答案:

答案 0 :(得分:1)

您的想法正确,但是您正在尝试比较单个字符。相反,在每次迭代中,您都应采用长度为k的子字符串,并将其与当前的“最小”和“最大”字符串进行比较:

public static String getSmallestAndLargest(String s, int k) {
    String curr = s.substring(0, k);
    String smallest = curr;
    String largest = curr;
    for (int i = 1; i < s.length() - k + 1; ++i) {
        curr = s.substring(i, i + k);
        if (smallest.compareTo(curr) > 0) {
            smallest = curr;
        }
        if (largest.compareTo(curr) < 0) {
            largest = curr;
        }
    }
    return smallest + "\n" + largest;
}

答案 1 :(得分:0)

我们将max和min初始化为大小为k的第一个子字符串。我们通过删除先前子字符串的第一个字符并添加新字符串的最后一个字符来遍历其余子字符串。我们跟踪按字典顺序排列的最大和最小。

public class GFG { 

public static void getSmallestAndLargest(String s, int k) 
{ 
    // Initialize min and max as first substring of size k 
    String currStr = s.substring(0, k); 
    String lexMin = currStr; 
    String lexMax = currStr; 

    // Consider all remaining substrings. We consider 
    // every substring ending with index i. 
    for (int i = k; i < s.length(); i++) { 
        currStr = currStr.substring(1, k) + s.charAt(i); 
        if (lexMax.compareTo(currStr) < 0)      
             lexMax = currStr; 
        if (lexMin.compareTo(currStr) > 0) 
             lexMin = currStr;             
    } 

    // Print result. 
    System.out.println(lexMin); 
    System.out.println(lexMax); 
} 

// Driver Code 
public static void main(String[] args) 
{ 
    String str = "GeeksForGeeks"; 
    int k = 3; 
    getSmallestAndLargest(str, k); 
} 

}