[LeetCode Daily Question] [Simple] 1370. Ascending and descending string

[LeetCode Daily Question] [Simple] 1370. Ascending and descending string

1370. Ascending and descending strings

1370. Ascending and descending strings

Algorithm idea: string

topic:

Insert picture description here

java code

  1. Count; count the number of occurrences of 26 letters;
  2. Forward traversal, reverse traversal, and piece together new strings;
class Solution {
    
    
    public String sortString(String s) {
    
    
		int[] m = new int[26];//计数
		for (char ch : s.toCharArray()) {
    
    //统计每个字母出现频率
			m[ch - 'a']++;
		}
		
		int count = 0;
		int n = s.length();
		StringBuffer res = new StringBuffer();
		
 		while (count < n) {
    
    
			for (int i = 0; i < 26; i++) {
    
    //正向遍历
				if (m[i] > 0) {
    
    
					res.append((char)('a' + i));
					count++;
					m[i]--;
				}
			}
			for (int i = 25; i >= 0; i--) {
    
    //反向遍历
				if (m[i] > 0) {
    
    
					res.append((char)('a' + i));
					count++;
					m[i]--;
				}
			}
		}
 		return res.toString();
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/110144389