面试题 01.06. 字符串压缩
class Solution {
public String compressString(String S) {
int N = S.length();
int i = 0;
StringBuilder sb = new StringBuilder();
while (i < N) {
int j = i;
while (j < N && S.charAt(j) == S.charAt(i)) {
j++;
}
sb.append(S.charAt(i));
sb.append(j - i);
i = j;
}
String res = sb.toString();
return res.length() < S.length()? res:S;
}
}
面试题58 - II. 左旋转字符串
//substring(int beginIndex, int endIndex) 方法返回字符串的子字符串。
class Solution {
public String reverseLeftWords(String s, int n) {
return s.substring(n) + s.substring(0, n);
}
}
class Solution {
public String reverseLeftWords(String s, int n) {
char[] chars = s.toCharArray();
reverse(chars, 0, n-1);
reverse(chars, n, chars.length-1);
reverse(chars, 0, chars.length-1);
return new String(chars);
}
private void reverse(char[] arr, int i, int j) {
while(i < j) {
char x = arr[i];
arr[i] = arr[j];
arr[j] = x;
i++;
j--;
}
}
}
class Solution {
public String reverseLeftWords(String s, int n) {
String sub = s.substring(n);
StringBuilder sb = new StringBuilder();
sb.append(sub);
String sub2 = s.substring(0, n);
sb.append(sub2);
return sb.toString();
}
}
class Solution {
public String reverseLeftWords(String s, int n) {
char [] res = new char[s.length()];
char [] temp = s.toCharArray();
System.arraycopy(temp,0,res,s.length() - n,n);
System.arraycopy(temp,n,res,0,s.length() - n);
return String.copyValueOf(res);
}
}
- system提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制.
面试题22. 链表中倒数第k个节点
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
if(head == null||head.next == null){
return head;
}
ListNode curr = head;
while( k>0 && curr != null){
curr = curr.next;
k--;
}
while(curr != null){
curr = curr.next;
head = head.next;
}
return head;
}
}
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode fast = head;
while(fast!=null) {
fast = fast.next;
if(k==0) {
head = head.next;
}else {
k--;
}
}
return head;
}
}
你知道的越多,你不知道的越多。
有道无术,术尚可求,有术无道,止于术。
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步