1. 旋轉(zhuǎn)字符串
給定一個(gè)字符串,要求把字符串前面的若干個(gè)字符移動(dòng)到字符串的尾部,如把字符串“abcdef”前面的2個(gè)字符'a'和'b'移動(dòng)到字符串的尾部,使得原字符串變成字符串“cdefab”。請(qǐng)寫(xiě)一個(gè)函數(shù)完成此功能,要求對(duì)長(zhǎng)度為n的字符串操作的時(shí)間復(fù)雜度為 O(n),空間復(fù)雜度為 O(1)。
手搖法
解法:
兩部分單獨(dú)反轉(zhuǎn),再整體反轉(zhuǎn)
2. 單詞翻轉(zhuǎn)
輸入一個(gè)英文句子,翻轉(zhuǎn)句子中單詞的順序,但單詞內(nèi)字符的順序不變,句子中單詞以空格符隔開(kāi)。為簡(jiǎn)單起見(jiàn),標(biāo)點(diǎn)符號(hào)和普通字母一樣處理。例如,輸入“I am a student.”,則輸出“student. a am I”。
解法:
和上面做法一樣,每部分單獨(dú)反轉(zhuǎn),再整體反轉(zhuǎn)
3. 鏈表翻轉(zhuǎn)
給出一個(gè)鏈表和一個(gè)數(shù)k,比如,鏈表為1→2→3→4→5→6,k=2,則翻轉(zhuǎn)后2→1→6→5→4→3,若k=3,翻轉(zhuǎn)后3→2→1→6→5→4,若k=4,翻轉(zhuǎn)后4→3→2→1→6→5,用程序?qū)崿F(xiàn)。
解法:
相當(dāng)于用【?!拷Y(jié)構(gòu),讓鏈表反轉(zhuǎn)
private TwoNodes reversePartOfList( Node node, int k ){
if( node == null || node.next == null ){
return null;
}
TwoNodes res = new TwoNodes();
int count = 1;
Node nextHead = node.next;
node.next = null; //把第一個(gè)放到棧底,沒(méi)有next
Node temp = null;
while( nextHead != null && count < k ){
temp = node; //記住棧頭
node = nextHead; //把新的一個(gè)放到棧底
nextHead = nextHead.next; //接著處理下一個(gè)
node.next = temp;
count++;
}
res.node1 = node;
res.node2 = nextHead;
return res;
}