Remove All Duplicate Lines in a File
题目:
.Given a text file, remove all the duplicate lines, maintaining the order such that the first occurrences of the lines stay in the same order.
解题思路:
这道题就是运用set+双指针的方法来解决。
代码:
.Given a text file, remove all the duplicate lines, maintaining the order such that the first occurrences of the lines stay in the same order.
解题思路:
这道题就是运用set+双指针的方法来解决。
代码:
public class RemoveAllDuplicateLinesinaFile { /* * google -> onsite -> google -> onsite -> wanted * fast * slow * the output should maintain the relative order in the * original string * */ public String remove(String s){ if(s == null || s.length() == 0){ return ""; } String[] strings = s.split("->"); int slow = 0; int fast = 0; int len = strings.length; Set<String> set = new HashSet<>(); while(fast <= len - 1){ if(set.contains(strings[fast])){ fast++; } else{ set.add(strings[fast]); strings[slow++] = strings[fast++]; } } StringBuilder sb = new StringBuilder(); // the last index should be slow int i = 0; while(i <= slow - 1){ sb.append(strings[i]); if(i != slow - 1){ sb.append("->"); } i++; } return sb.toString(); } public static void main(String[] args){ RemoveAllDuplicateLinesinaFile removeAllDuplicateLinesinaFile = new RemoveAllDuplicateLinesinaFile(); String s = "google->onsite->google->onsite->wanted"; String rst = removeAllDuplicateLinesinaFile.remove(s); System.out.println(rst); } }

Comments
Post a Comment