將所有大寫字元移動到所有小寫字元之前的最小操作次數
給定一個字串 'str',其中包含大寫和小寫字母。任何小寫字元都可以透過單個操作更改為大寫字元,反之亦然。目標是列印此過程中所需的最小操作次數,以生成一個至少包含一個小寫字元,然後至少包含一個大寫字元的字串。
輸入輸出場景
第一種可能的解決方案:前 4 個字元可以轉換為大寫字元,即“TUTORial”,需要 4 次操作。
輸入
str = “tutoRial”
輸出
1
第二種可能的解決方案:第三個字元可以轉換為小寫字元,即“tutorial”,需要 1 次操作。
輸入
str = “point”
輸出
0
字串已採用指定的格式。
有兩種可能的結果
透過確定最後一個大寫字元的索引,字串中的所有小寫字元都應轉換為大寫字元。
或者,獲取字串中第一個小寫字元的索引,並將之後的所有大寫字母轉換為小寫字母。
選擇操作次數最少的方案。
Java 實現
讓我們瞭解一下這種方法的 Java 實現
示例
public class Main {
public static int minOperationsLower(String str, int n) {
// Store the indices of the last uppercase character and the first lowercase character
int i, lastUpperCase = -1, firstLowerCase = -1;
for (i = n - 1; i >= 0; i--) { //finding uppercase
if (Character.isUpperCase(str.charAt(i))) {
lastUpperCase = i;
break;
}
}
for (i = 0; i < n; i++) { //finding lowercase
if (Character.isLowerCase(str.charAt(i))) {
firstLowerCase = i;
break;
}
}
if (lastUpperCase == -1 || firstLowerCase == -1)
return 0;
// Counting of uppercase characters that appear after the first lowercase character
int countUpperCase = 0;
for (i = firstLowerCase; i < n; i++) {
if (Character.isUpperCase(str.charAt(i))) {
countUpperCase++;
}
}
// Count of lowercase characters that appear before the last uppercase character
int countLowerCase = 0;
for (i = 0; i < lastUpperCase; i++) {
if (Character.isLowerCase(str.charAt(i))) {
countLowerCase++;
}
}
// Return the minimum operations required
return Math.min(countLowerCase, countUpperCase);
}
// main method
public static void main(String args[]) {
String str = "tutoRIalsPoinT";
int n = str.length();
System.out.println("Operations Required: "+minOperationsLower(str, n));
}
}
輸出
Operations Required: 4
時間複雜度:O(N),其中 N 是字串的長度
空間複雜度:O(1),未使用額外空間。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP