Reverse Words in a String问题及解法

本文介绍了一种通过将输入字符串按单词分割并反转的方法来解决特定问题的算法。具体实现使用了C++语言,并通过istringstream来读取单词,再将它们以反转的顺序重新组合。

问题描述:

Given an input string, reverse the string word by word.

示例:
Given s = "the sky is blue",
return "blue is sky the".

问题分析:

可将字符串分割成子串数组,最后再将字串数组reverse即可。


过程详见代码:

class Solution {
public:
    void reverseWords(string &s) {
        if(s == "") return;
        stringstream ss(s);
		string t = "";
		string res="";
		while (ss >> t)
		{
			res = t + " " + res;
		}
        if(t != "")
		    res.pop_back();
		s = res;
    }
};


import java.util.*; class TrieNode { TrieNode[] children; int index; List<Integer> palindromeIndices; public TrieNode() { children = new TrieNode[26]; index = -1; palindromeIndices = new ArrayList<>(); } } class Solution { public List<List<Integer>> palindromePairs(String[] words) { List<List<Integer>> result = new ArrayList<>(); TrieNode root = buildTrie(words); for (int i = 0; i < words.length; i++) { search(words, i, root, result); } return result; } private TrieNode buildTrie(String[] words) { TrieNode root = new TrieNode(); for (int i = 0; i < words.length; i++) { String reversed = new StringBuilder(words[i]).reverse().toString(); TrieNode node = root; for (int j = 0; j < reversed.length(); j++) { if (isPalindrome(reversed, j, reversed.length() - 1)) { node.palindromeIndices.add(i); } int index = reversed.charAt(j) - 'a'; if (node.children[index] == null) { node.children[index] = new TrieNode(); } node = node.children[index]; } node.index = i; node.palindromeIndices.add(i); } return root; } private void search(String[] words, int i, TrieNode root, List<List<Integer>> result) { String word = words[i]; for (int j = 0; j < word.length(); j++) { // 情况1:非完全匹配且剩余部分是回文 if (root.index != -1 && root.index != i && isPalindrome(word, j, word.length() - 1)) { result.add(Arrays.asList(i, root.index)); } int index = word.charAt(j) - 'a'; if (root.children[index] == null) return; root = root.children[index]; } // 情况2:完全匹配 if (root.index != -1 && root.index != i) { result.add(Arrays.asList(i, root.index)); } // 情况3:处理剩余回文路径(排除完全匹配的情况) for (int idx : root.palindromeIndices) { if (idx != i) { result.add(Arrays.asList(i, idx)); } } } private boolean isPalindrome(String s, int left, int right) { while (left < right) { if (s.charAt(left++) != s.charAt(right--)) return false; } return true; } } 具体解释这段代码,特别是buildtrie和search,让我一个初学者可以理解
05-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值