/* a simple simulation of the swap behavior using dual pointer pointing to the first and last element, then step by step swap two pointed elements and swap them until the two pointer pointing to the same element */ classSolution { publicvoidreverseString(char[] s) {
intleft=0; intright= s.length - 1; char temp;
while (left < right) { //swap the pointed two elements temp = s[left]; s[left] = s[right]; s[right] = temp;
left++; right--; } } }
LeetCode 541.反转字符串II
给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。
classSolution { public String reverseStr(String s, int k) { int quotient, remiander; quotient = s.length() / (2 * k); remiander = s.length() % (2 * k);
char[] str = s.toCharArray();
// for (int i = 0; i < quotient; i++) { // reverseFromTo(str, i * 2 * k, i * 2 * k + k - 1); // }
// if ( remiander / k == 0){ // reverseFromTo(str, quotient * 2 * k, str.length - 1); // }else if (remiander / k >= 1) { // reverseFromTo(str, quotient * 2 * k, quotient * 2 * k - 1 + k); // }
for (inti=0; i < str.length; i += 2 * k) { reverseFromTo(str, i, Math.min(i+k, str.length) - 1); }
returnnewString(str);
}
privatevoidreverseFromTo(char[] chars, int startIndex, int endIndex) { char temp; while (startIndex < endIndex) { //swap the pointed two elements temp = chars[startIndex]; chars[startIndex] = chars[endIndex]; chars[endIndex] = temp;
publicclassSolution { public String replaceSpace(String s) { intcnt=0; char[] str = s.toCharArray(); // count the numer of space first to decide the length of the new array for (inti=0; i < str.length; i++) { charc= str[i]; if (c == ' '){ cnt ++; } } // actually, there is no need for this counting, we can directly claim // a new array, whose size is triple the previous one which is definitly // enough for our use char[] ans = newchar[str.length + 2 * cnt]; for (inti=0, j = 0; i < str.length; i++) { if (str[i] != ' '){ ans[j++] = str[i]; }else{ ans[j++] = '%'; ans[j++] = '2'; ans[j++] = '0'; } }